Dynamically P/Invoking a DLL
Question
What is the best way to dynamically P/Invoke unmanaged code from .NET?
For example, I have a number of unmanaged DLL's with common C-style exports between them. I would like to take the path to a DLL and then P/Invoke a function based on the exported name. I would not know the DLL name until runtime.
Basically, what is the equivalent of LoadLibrary
and GetProcAddress
for .NET? (I have existing code which uses these functions to accomplish the same goal, entirely in unmanaged code).
Solution
This article describes a typesafe managed wrapper for GetProcAddress that should help you out.
http://blogs.msdn.com/jmstall/archive/2007/01/06/Typesafe-GetProcAddress.aspx
OTHER TIPS
You can do this by P/Invoking into LoadLibrary and GetProcAddress, and then using Marshal.GetDelegateForFunctionPointer.
For details, see this article.
Also see this blog post from Jonathan Swift title Dynamically calling an unmanaged dll from .net
One option you have is to create a native function which is responsible for loading the appropriate DLL and function into memory and then returning that function to managed code based on your path. This way you can use the GetProcAddress trick naturally and return the function point. You can then PInvoke into this function and get back a Delegate which will then invoke into the proper DLL.