3F / DllExport

.NET DllExport with .NET Core support (aka 3F/DllExport aka DllExport.bat)
MIT License
937 stars 131 forks source link

FreeLibrary() does not work as expected: file still in use #213

Closed Scalibq closed 1 year ago

Scalibq commented 1 year ago

The question is related to:

I am working on a plugin system where I dynamically load or unload DLLs at runtime via LoadLibrary()/FreeLibrary(). For DLLs developed with C++, either natively or with use of CLR, this works correctly. When I use DllExport to create a plugin in C# (.NET 4.8, Visual Studio 2022), I find that FreeLibrary() does not work as expected: After I call FreeLibrary(), the file is still in use (so it cannot be deleted or overwritten).

Since LoadLibrary()/FreeLibrary() is reference-counted, I tried calling it multiple times. I found that it can be called two times successfully, so apparently something inside the DLL had increased the reference-count as well.

However, even though FreeLibrary() fails after two calls, the file still remains in use, so it still cannot be deleted or overwritten.

I have tested with a minimal DLL which only exports some basic functions that return a string, and does not load any other assemblies, libraries, or creates any objects, threads or anything, to rule out any possible problems. Then I just tested by doing LoadLibrary(), GetProcAddress(), calling the function to retrieve a string, and then FreeLibrary() again.

I am not sure if this is a bug or if I need to implement some special shutdown/cleanup code somewhere in my DLL for this to work correctly?

3F commented 1 year ago

Hello,

It's a duplicate, #207, #157, #118

And since for current version we can't use something like modern loading via context (somehow), I recommend the classic intermediate loading of the final PE module. That is, for example, direct memory if module is tiny or fs copy/rename same to vsix plugin system in Visual Studio IDE etc.