Enable multiple Node-API hosting JS engines / runtimes to share the global Node-API functions #329
+449
−3
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Stacked on #328.
This is my suggestion for adding "multi-host" support to
weak-node-api, enabling multiple engines implementing Node-API to co-exist and share the Node-API function namespace. While not needed specifically for bringing Node-API to React Native adding this could makeweak-node-apimore applicable in other scenarios where multiple engines implementing Node-API share a single process.I'm proposing adding mechanisms to "wrap" the opaque pointers of specific Node-API implementors with:
Where
Tis constrained to one of:napi_envnode_api_basic_env(an alias fornapi_envwith slightly altered semantics)napi_threadsafe_functionnapi_async_cleanup_hook_handleThese
Wrappedobjects can then be passed around like their respective opaque pointers and "unwrapped" in the internal implementation of the "multi host" implementation of Node-API functions.Wrappedobjects are created calling one of these instance methods onWeakNodeApiMultiHost:These functions are called internally in
napi_create_threadsafe_functionandnapi_add_async_cleanup_hook.Usage
WeakNodeApiMultiHost(callingmulti_host.wrap(original_env, host);)react-native-node-api/packages/weak-node-api/tests/test_multi_host.cpp
Lines 18 to 52 in f79a30b
Open questions
std::functioninstead of raw function pointers for all (or some) of theWeakNodeApiHostmembers? This would allow capturing lambdas, making it much easier to provide a meaningful implementation of for examplenapi_module_register.Wrappedobjects be owned by theWeakNodeApiMultiHostobject (at least for now), but could we make memory management more efficient to release theWrapped<T>before theWeakNodeApiMultiHostdeletion: Innapi_remove_async_cleanup_hookor some of thenapi_*_threadsafe_functionfunctions?Generated code
Below are samples from the generated code:
napi_create_objectimplementationnapi_create_threadsafe_functionandnapi_add_async_cleanup_hookimplementationsNotice the calls to
wrap, wrapping their opaque "out" pointers.