Skip to main content

Exposing C Functions to JavaScript

This tutorial shows how to create native C modules that can be called from JavaScript code.

Simple Function Example

We’ll create a Fibonacci function in C and expose it to JavaScript.
1

Create the C module

Create fib.c with the native implementation:
Key components:
  1. Native implementation - The fib() function in pure C
  2. JavaScript wrapper - js_fib() handles type conversion between JS and C
  3. Export list - Declares which functions to expose
  4. Module initialization - Sets up the module exports
  5. Entry point - js_init_module() is called when the module is loaded
2

Compile the native module

Compile the C code into a shared library:On Linux/macOS:
On Windows:
3

Create a test JavaScript file

Create test_fib.js to test the native module:
This code:
  • Detects the platform to load the correct library extension
  • Dynamically imports the native module
  • Calls the native fib() function
4

Run the example

Execute the test file:
Expected output:
The --std flag enables the standard library, which includes the qjs:os module.

Creating a Native Class

For more complex scenarios, you can expose entire classes. See the Point class example which demonstrates:
  • Creating a JavaScript class backed by C data structures
  • Implementing getters and setters
  • Adding methods to the prototype
  • Proper memory management with finalizers
  • Class inheritance support

Type Conversion Functions

JavaScript to C:
  • JS_ToInt32(ctx, &n, val) - Convert to 32-bit integer
  • JS_ToFloat64(ctx, &d, val) - Convert to double
  • JS_ToCString(ctx, val) - Convert to C string
  • JS_ToBool(ctx, val) - Convert to boolean
C to JavaScript:
  • JS_NewInt32(ctx, n) - Create integer value
  • JS_NewFloat64(ctx, d) - Create number value
  • JS_NewString(ctx, str) - Create string value
  • JS_NewBool(ctx, b) - Create boolean value
  • JS_UNDEFINED, JS_NULL - Special values

Next Steps