Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

pinvoke

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?

like image 770
LCC Avatar asked Sep 30 '11 05:09

LCC


1 Answers

You do it the same way. Declare a delegate type whose signature matches the exported function, just like SomeFuncSig. Pinvoke LoadLibrary and GetProcAddress to get the IntPtr for the exported function, just like you did in C++. Then create the delegate object with Marshal.GetDelegateForFunctionPointer().

like image 64
Hans Passant Avatar answered Oct 20 '22 17:10

Hans Passant