Writing native modules in C for QuickJS engine

Basic introduction to native C modules for QuickJS

QuickJS is not a kind of NodeJS, it’s more like V8

Getting started

Goal

my_module.js

Prepare the source

# compile
./qjsc -m -o my_module my_module.js
# run
./my_module
ReferenceError: could not load module filename 'my_module'

Add the module name to the compiler

...
/* add system modules */
namelist_add(&cmodule_list, "std", "std", 0);
namelist_add(&cmodule_list, "os", "os", 0);
// our module
namelist_add(&cmodule_list, "my_module", "my_module", 0);
...
# This will build the compiler only, it's faster
make qjsc
# Test again
./qjsc -m -o my_module my_module.js
/tmp/ccenbi7V.o: In function `main’:
out19678.c:(.text.startup+0x84): undefined reference to `js_init_module_my_module’
collect2: error: ld returned 1 exit status

Native module template

my_module.c
int a;
JS_ToInt32(ctx, &a, argv[0])

Adding the C code to Makefile

QJS_LIB_OBJS= ... $(OBJDIR)/my_module.o
# build the compiler
make qjsc
# compile our example code
./qjsc -m -o my_module my_module.js
# run the program
./my_module
output => Result 5
./qjsc -flto -m -o my_module my_module.js

Software Developer ~

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store