Skip to main content

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 context
  • func - Pointer to the C function implementation
  • name - Name of the function as it appears in JavaScript
  • length - The length property of the function (expected argument count)

Returns

Returns a new JavaScript function object.

C Function Signature

Example

From examples/fib.c:

JS_NewCFunction2

Create a JavaScript function with more control over its type and behavior.

Parameters

  • ctx - The JavaScript context
  • func - Pointer to the C function
  • name - Function name
  • length - The length property
  • cproto - 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 context
  • obj - The object to add properties to
  • tab - Array of function list entries
  • len - Number of entries in the array

Returns

Returns 0 on success, -1 on error.

Example

From examples/fib.c:
From 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 JSValueConst parameters (they don’t need to free them)
  • C functions must return a newly allocated JSValue
  • Always return JS_EXCEPTION on error after setting an exception with JS_Throw* functions
  • There is no implicit stack - parameters are passed as normal C function arguments