Creating C Functions
C functions can be exposed to JavaScript using QuickJS’s function creation APIs.JS_NewCFunction
Create a simple JavaScript function backed by C code.Parameters
ctx- The JavaScript contextfunc- Pointer to the C function implementationname- Name of the function as it appears in JavaScriptlength- Thelengthproperty of the function (expected argument count)
Returns
Returns a new JavaScript function object.C Function Signature
Example
Fromexamples/fib.c:
JS_NewCFunction2
Create a JavaScript function with more control over its type and behavior.Parameters
ctx- The JavaScript contextfunc- Pointer to the C functionname- Function namelength- Thelengthpropertycproto- Function type (constructor, getter, setter, etc.)magic- Magic value passed to the function
Function Types
Example
JS_SetPropertyFunctionList
Convenience function to add multiple functions to an object at once.Parameters
ctx- The JavaScript contextobj- The object to add properties totab- Array of function list entrieslen- Number of entries in the array
Returns
Returns 0 on success, -1 on error.Example
Fromexamples/fib.c:
examples/point.c:
Helper Macros
JS_CFUNC_DEF
Define a regular function.JS_CGETSET_MAGIC_DEF
Define a getter/setter pair with a magic value.JS_CFUNC_MAGIC_DEF
Define a function with a magic value.Notes
- C functions receive constant
JSValueConstparameters (they don’t need to free them) - C functions must return a newly allocated
JSValue - Always return
JS_EXCEPTIONon error after setting an exception withJS_Throw*functions - There is no implicit stack - parameters are passed as normal C function arguments