1 year ago

#279829

test-img

Mre Sie

FreeLibrary not working on Loaded C++ DLL

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

c#

curl

dll

kernel32

0 Answers

Your Answer

Accepted video resources