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.Create the C module
Create Key components:
fib.c with the native implementation:- Native implementation - The
fib()function in pure C - JavaScript wrapper -
js_fib()handles type conversion between JS and C - Export list - Declares which functions to expose
- Module initialization - Sets up the module exports
- Entry point -
js_init_module()is called when the module is loaded
Create a test JavaScript file
Create This code:
test_fib.js to test the native module:- Detects the platform to load the correct library extension
- Dynamically imports the native module
- Calls the native
fib()function
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 integerJS_ToFloat64(ctx, &d, val)- Convert to doubleJS_ToCString(ctx, val)- Convert to C stringJS_ToBool(ctx, val)- Convert to boolean
JS_NewInt32(ctx, n)- Create integer valueJS_NewFloat64(ctx, d)- Create number valueJS_NewString(ctx, str)- Create string valueJS_NewBool(ctx, b)- Create boolean valueJS_UNDEFINED,JS_NULL- Special values
Next Steps
- Learn about JavaScript modules
- Explore bytecode compilation
- See the complete Point class example