Reload a DLL which has been imported with DllImport

孤街浪徒 提交于 2019-12-22 05:04:09

问题


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.


回答1:


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.




回答2:


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);



回答3:


Rather than using DllImport to import the DLL, you could try using LoadModule (from WinAPI) to do so, and then use GetProcAddress and FreeLibrary to do what you need as far as calling functions in it and unloading/reloading it.

See here.

Might be a bit prettier/manageable if you used C++/CLR to glue C# and the unmanaged DLL together.



来源:https://stackoverflow.com/questions/13967448/reload-a-dll-which-has-been-imported-with-dllimport

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!