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
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