Search code examples
c#pinvoke

PInvoke when you don't know the DLL at compile time?


In C#, I'm trying to PInvoke a "simple" function I have in C++. The issue is that I don't 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.

For the life of me I can't figure out how to do this in C#. I wouldn't have any trouble if I knew the dll name, 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 do I do this without knowing the dll I'm loading from at compile time?


Solution

  • Thee is a solution here: Dynamically calling an unmanaged dll from .NET (C#) (based on LoadLibrary/GetProcAddress)