Status: Experimental
This library uses a combination of C# Source Generators and .NET Native AOT Deployment to produce Node.js native addons written in C# that do not depend on the .NET runtime.
-
.NET 7 or later is required at build time because this project relies on recent improvements to .NET native AOT capabilities.
-
This is only tested on Windows so far. In principle this should work on any platform supported by .NET Native AOT, but it may require some tweaks.
dotnet publish -r win-x64
Select an appropriate .NET runtime identifier for your platform, or even a different platform for cross-compilation.
node .\Example\Example.js
The simple example script uses require()
to load the native module that was just built, and calls a method on it.
- A C# class defines some instance properties and methods to be exposed to Node.js as a module. See the example class.
- The module class is tagged with a
[NodeApi.Module]
attribute. (In the future, additional C# classes in the same library may be exported indirectly via properties on the module.) - At build time, the source generator finds the class with that attribute and then emits code to register the module as a Node-API addon and export the module class's properties and methods.
- The registration method has a special
[UnmanagedCallersOnly]
attribute that causes it to be exported from the native library as an ordinary native entrypoint. - When Node.js loads the module, it calls the registration method like any other native entrypoint.
- Helper classes in the .NET
NodeApi
library in this project facilitate interop and marshalling between a Node addon object model and low-levelnapi_
functions that are called via P/Invoke.
The intention for the NodeApi
helper classes here is to follow a similar pattern to the node-addon-api
C++ classes, with some minor differences allowing for .NET conventions.