PInvoke, when you do not know the DLL at compile time?

In C #, I try PInvoke the "simple" function that I have in C ++. The problem is that I do not know the name or location of the library at compile time. In C ++, this is easy:

typedef HRESULT (*SomeFuncSig)(int, IUnknown *, IUnknown **); const char *lib = "someLib.dll"; // Calculated at runtime HMODULE mod = LoadLibrary(lib); SomeFuncSig func = (SomeFuncSig)GetProcAddress("MyMethod"); IUnknown *in = GetSomeParam(); IUnknown *out = NULL; HRESULT hr = func(12345, in, &out); // Leave module loaded to continue using foo. 

In life, I can't figure out how to do this in C #. I would not have a problem if I knew the name dll, it would look something like this:

 [DllImport("someLib.dll")] uint MyMethod(int i, [In, MarshalAs(UnmanagedType.Interface)] IUnknown input, [Out, MarshalAs(UnmanagedType.Interface)] out IUnknown output); 

How can I do this without knowing the dll with which I boot at compile time?

+6
source share
3 answers

This solution is here: Dynamically invoking an unmanaged dll from .NET (C #) (based on LoadLibrary / GetProcAddress)

+5
source

You do the same. Declare the type of delegate whose signature corresponds to the exported function, just like SomeFuncSig. Pinvoke LoadLibrary and GetProcAddress to get IntPtr for the exported function, as in C ++. Then create the delegate object using Marshal.GetDelegateForFunctionPointer ().

+7
source

If you know the name of the DLL in advance and know the names of the functions in advance, there is an easier way.

You can simply declare P / Invoke signatures and then use LoadLibrary to load the DLL based on, for example, a configuration file entry. As long as you successfully call LoadLibrary before any of the P / Invoke functions are used, they will succeed because the DLL is already loaded.

+1
source

Source: https://habr.com/ru/post/898340/


All Articles