Embedding QuickJS in Applications
QuickJS can be embedded in C/C++ applications to add JavaScript scripting capabilities. The C API is designed to be simple and efficient.Basic Concepts
Runtime and Contexts
JSRuntime represents a JavaScript runtime with its own object heap. Multiple runtimes can exist simultaneously but cannot exchange objects.
JSContext represents a JavaScript context (or Realm). Each context has its own global objects. Multiple contexts can exist per runtime and share objects, similar to same-origin frames in a browser.
JSValue
JSValue represents a JavaScript value (primitive or object). QuickJS uses reference counting, so you must explicitly:
- Duplicate:
JS_DupValue()- increments reference count - Free:
JS_FreeValue()- decrements reference count
Minimal Embedding Example
#include <quickjs.h>
#include <stdio.h>
int main(void) {
JSRuntime *rt;
JSContext *ctx;
// Create runtime
rt = JS_NewRuntime();
if (!rt) {
fprintf(stderr, "Failed to create runtime\n");
return 1;
}
// Create context
ctx = JS_NewContext(rt);
if (!ctx) {
fprintf(stderr, "Failed to create context\n");
JS_FreeRuntime(rt);
return 1;
}
// Evaluate JavaScript
const char *code = "1 + 2";
JSValue result = JS_Eval(ctx, code, strlen(code), "<input>", JS_EVAL_TYPE_GLOBAL);
// Check for exceptions
if (JS_IsException(result)) {
JSValue exception = JS_GetException(ctx);
const char *str = JS_ToCString(ctx, exception);
fprintf(stderr, "Exception: %s\n", str);
JS_FreeCString(ctx, str);
JS_FreeValue(ctx, exception);
} else {
// Convert result to C string
const char *str = JS_ToCString(ctx, result);
printf("Result: %s\n", str);
JS_FreeCString(ctx, str);
}
JS_FreeValue(ctx, result);
Runtime Configuration
Memory Limits
Stack Size
Runtime Information
Exposing C Functions
Simple C Function
Function List
Type Conversions
JavaScript to C
C to JavaScript
Exception Handling
Most C API functions can returnJS_EXCEPTION. Always check for exceptions:
Evaluation Flags
JS_EVAL_TYPE_GLOBAL- Global script (default)JS_EVAL_TYPE_MODULE- ES6 moduleJS_EVAL_FLAG_STRICT- Force strict modeJS_EVAL_FLAG_COMPILE_ONLY- Compile but don’t executeJS_EVAL_FLAG_BACKTRACE_BARRIER- Don’t include prior frames in backtraces
Next Steps
- Native Modules - Create loadable C modules
- Memory Management - Custom allocators and limits
- Performance - Optimize your embedded JavaScript