Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload a DLL which has been imported with DllImport

Tags:

c#

.net

dllimport

My C# application (.NET Framework 4.0) imports an external unmanaged DLL with the following code:

[DllImport("myDLL.dll"), EntryPoint="GetLastErrorText"]
private static extern IntPtr GetLastErrorText();

Unfortunately there seems to be a bug in the third-party DLL. As a workaround I would need to unload the DLL and reload it afterwards. How can I do this? I've seen several posts but they all talk about managed DLLs.

like image 215
Robert Strauch Avatar asked Dec 20 '12 07:12

Robert Strauch


2 Answers

You can write a wrapper around the library that manages the access to it. Then you can use native methods to call the library. Take a look at this blog post.

like image 76
Carsten Avatar answered Sep 19 '22 12:09

Carsten


I think you'll need to go down to using LoadLibrary/FreeLibrary/GetProcAddress as shown in Difference between dllimport and getProcAddress : Abbreviated sample (no error handling) below:

   [UnmanagedFunctionPointer(CallingConvention.StdCall)]
   private delegate Bool BarType(Byte arg); 
   ...
   IntPtr pDll= LoadLibrary("foo.dll");
   IntPtr pfunc = GetProcAddress(pDll, "bar");
   BarType bar = (BarType)Marshal.GetDelegateForFunctionPointer(pFunc, typeof(BarType));
   var ok = bar(arg);
   FreeLibrary(pDll);
like image 36
Alexei Levenkov Avatar answered Sep 20 '22 12:09

Alexei Levenkov