Binding C Functions

Whether you're embedding Kuroko in an application or writing an extension module, binding a C function is something you'll want to do.

The Easy Way

#include <kuroko/kuroko.h>
#include <kuroko/vm.h>
#include <kuroko/util.h>
KRK_Function(myfunction) {
return INTEGER_VAL(myarg*myarg);
int main(int argc, char *argv[]) {
BIND_FUNC(vm.builtins, myfunction);
return 0;
Top-level header with configuration macros.
void krk_freeVM(void)
Release resources from the VM.
Definition: vm.c:992
void krk_initVM(int flags)
Initialize the VM at program startup.
Definition: vm.c:904
Utilities for creating native bindings.
Core API for the bytecode virtual machine.
#define vm
Convenience macro for namespacing.
Definition: vm.h:267
KrkInstance * krk_startModule(const char *name)
Set up a new module object in the current thread.
Definition: vm.c:3180
KrkValue krk_interpret(const char *src, char *fromFile)
Compile and execute a source code input.
Definition: vm.c:3190

This demo uses the utility macros provided in <kuroko/util.h> to easily create a function with argument checking and bind it to the builtin namespace.

KRK_Function() takes care of the function signature and function naming for exception messages.

FUNCTION_TAKES_EXACTLY() provides simple argument count validation. FUNCTION_TAKES_AT_LEAST() and FUNCTION_TAKES_AT_MOST() are also available.

CHECK_ARG() validates the type of arguments passed to the function and unboxes them to C types.

INTEGER_VAL() converts a C integer to a Kuroko int value.

BIND_FUNC() binds the function to a namespace table.

The Hard Way

While the macros above provide a convenient way to bind functions, they are just wrappers around lower-level functionality of the API.

#include <kuroko/kuroko.h>
#include <kuroko/vm.h>
static KrkValue myfunction(int argc, KrkValue argv[], int hasKw) {
int myarg;
if (argc != 1) return krk_runtimeError(vm.exceptions->argumentError, "myfunction() expects exactly 1 argument, %d given", argc);
if (!IS_INTEGER(argv[0])) return krk_runtimeError(vm.exceptions->typeError, "expected int, not '%T'", argv[0]);
myarg = AS_INTEGER(argv[0]);
return INTEGER_VAL(myarg*myarg);
int main(int argc, char *argv[]) {
krk_defineNative(&vm.builtins->fields, "myfunction", myfunction);
krk_interpret("print(myfunction(42))", "<stdin>");
return 0;
KrkValue krk_runtimeError(KrkClass *type, const char *fmt,...)
Produce and raise an exception with a formatted message.
Definition: exceptions.c:445
KrkNative * krk_defineNative(KrkTable *table, const char *name, NativeFn function)
Attach a native C function to an attribute table.
Definition: vm.c:194
Stack reference or primative value.