Home > OS >  Unloading NativeAOT compiled dll
Unloading NativeAOT compiled dll

Time:12-10

With .NET 7's NativeAOT compilation. We can now load a C# dll as regular Win32 module.

HMODULE module = LoadLibraryW("AOT.dll");
auto hello = GetProcAddress(module, "Hello");
hello();

This works fine and prints some stuff in console.

However, when unloading the dll. It simply doesn't work. No matter how many times I call FreeLibrary("AOT.dll"), GetModuleHandle("AOT.dll") still returns the handle to the module, implying that it did not unload successfully.

My "wild guess" was that the runtime has some background threads still running (GC?), so I enumerated all threads and use .NET calling GetModuleHandleEx

So I hooked GetModuleHandleEx to intercept calls and shift out the flag. Ta-da! Now I can unload the NativeAOT compiled dll without any problems.

I know this approach is quite hacky, but hey, it works. If anyone happen to have a better solution, please let me know.

  • Related