This appropriately named package allows you to safely define a DllMain function for your NativeAOT library in C.
Add the DllMain NuGet package to your project, then follow the instructions from readme.txt.
The NativeAOT toolchain declares multiple MSBuild targets to build/link the NativeAOT library. Among other things, it injects an object file that defines an empty DllMain function, in an effort to avoid user-defined DllMain .NET implementations, since the NativeAOT runtime doesn't support initialization under DllMain's loader lock.
This package declares another target that gets injected between SetupOSSpecificProps (which builds LinkerArg) and LinkNative (which calls the linker with those arguments). This target:
- Builds the user-defined
.cfile, - Removes the toolchain-defined object file with an empty
DllMainfrom linker arguments, - Adds compiled user-defined C code to linker arguments.
- Forces the linker to include the otherwise unreferenced new
DllMainfunction in the final library.
As long as the user doesn't call managed code from their DllMain function, the resulting library should not break any rules imposed by the OS or the NativeAOT runtime/toolchain.