Overview
Embedding the Dart VM involves:- Initializing the VM with configuration and callbacks
- Creating and managing isolates
- Loading and executing Dart code
- Providing native function implementations
- Cleaning up resources on shutdown
Initialization
Setting Up VM Parameters
TheDart_InitializeParams structure configures VM initialization.
Must be set to DART_INITIALIZE_PARAMS_CURRENT_VERSION
Buffer containing VM snapshot data or NULL. Must remain valid until Dart_Cleanup().
Buffer containing snapshot instructions or NULL. Must remain valid until Dart_Cleanup().
Required callback for creating new isolate groups
Optional callback invoked before isolate shutdown (can run Dart code)
Optional callback invoked after isolate shutdown (cannot run Dart code)
Basic Initialization Example
Isolate Lifecycle Callbacks
Dart_IsolateGroupCreateCallback
Dart_InitializeIsolateCallback
Dart_IsolateShutdownCallback
Dart_IsolateCleanupCallback
Creating and Running Isolates
Complete Isolate Creation
Loading Dart Code
From Kernel (Recommended)
Kernel files (.dill) are the recommended format for loading Dart code in embedded scenarios.From Snapshots
Snapshots provide faster startup for AOT-compiled code.Calling Dart from C
Invoking Functions
Accessing Fields
Complete Embedding Example
File I/O Callbacks
Provide file I/O callbacks if your Dart code needs file access.Best Practices
- Snapshot Management - Keep snapshot buffers valid for the lifetime of isolates using them
- Error Handling - Always check return values and handle errors appropriately
- Resource Cleanup - Use cleanup callbacks to free embedder-allocated resources
- Thread Safety - Only one thread can be in an isolate at a time; use proper synchronization
- Scope Management - Balance Dart_EnterScope()/Dart_ExitScope() calls
- Isolate Data - Use isolate_group_data for shared context, isolate_data for per-isolate context
Common Patterns
Event Loop Integration
Multi-Isolate Management
See Also
- Dart VM C API Overview - Complete API reference
- Native Extensions - Creating native extensions