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
KRK_Function(myfunction) {
FUNCTION_TAKES_EXACTLY(1);
CHECK_ARG(0,int,krk_integer_type,myarg);
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.
void krk_initVM(int flags)
Initialize the VM at program startup.
Utilities for creating native bindings.
Core API for the bytecode virtual machine.
#define vm
Convenience macro for namespacing.
KrkValue krk_interpret(const char *src, const char *fromFile)
Compile and execute a source code input.
KrkInstance * krk_startModule(const char *name)
Set up a new module object in the current thread.
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.
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[]) {
return 0;
}
KrkValue krk_runtimeError(KrkClass *type, const char *fmt,...)
Produce and raise an exception with a formatted message.
KrkNative * krk_defineNative(KrkTable *table, const char *name, NativeFn function)
Attach a native C function to an attribute table.
Stack reference or primative value.