2

I'm using an external DLL which is written in C++. It's a cURL Wrapper. I do not have access the code, just DLL.

//Import kernel32 DLL
static class NativeMethods
{
    [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string dllToLoad);

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

    [DllImport("kernel32.dll")]
    public static extern bool FreeLibrary(IntPtr hModule);
}

//Create delegate function
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int curlInit(ref CurlSettings settings);

//Import library
dllPointer = NativeMethods.LoadLibrary(DLLPath);
ptrInit = NativeMethods.GetProcAddress(dllPointer, "curlInit");
var initFunction = (curlInit)Marshal.GetDelegateForFunctionPointer(ptrInit, typeof(curlInit));

initFunction(ref defaultSettings); <-- This works

//Try to get rid of this DLL
initFunction = null;
NativeMethods.FreeLibrary(dllPointer);
GC.Collect();

//Load library again
...
...

initFunction(ref defaultSettings); <-- Raise and error

I need to initialize cURL, everytime I changed a setting.

For the first time, init function works perfectly. However when I try it second time, init function return error value (even with the same params), so I get that DLL and resources not removed successfully.

What I tried:

  • I set everything I used, to NULL,
  • I called FreeLibrary
  • I called my boy, GC.Collect()

Any idea?

Edit: NativeMethods.FreeLibrary(dllPointer); return True

Alexander
  • 1,232
  • 1
  • 15
  • 24
Mre Sie
  • 31
  • 1
  • are you using any of this library function with `DllImport` between free and load again? – Selvin Mar 11 '22 at 15:06
  • 2
    Be aware that some DLLs can effectively render themselves not unloadable if they install certain hooks that they want to run at process exit, for example. Without being able to inspect the code it's difficult to know if you're in that situation. – Damien_The_Unbeliever Mar 11 '22 at 15:06
  • See e.g. [This question](https://stackoverflow.com/q/48631560/15498), as an example – Damien_The_Unbeliever Mar 11 '22 at 15:07

0 Answers0