I have a code like this one in a DLL:
int (*callback)(int a, int b);
void mainfunc()
{
callback(1, 2);
callback(3, 4);
}
To access this DLL from a C program, I used to do this:
#include <windows.h>
int callback(int a, int b) {return a+b;}
int main()
{
HANDLE dll = LoadLibrary("test.dll");
*(void**)GetProcAddress(dll, "callback") = (void*)callback;
((void(*))GetProcAddress(dll, "mainfunc"))();
FreeLibrary(dll);
}
The DLL is still C code, but the main program have switched to C#. How to deal with function pointer? How would that code be in C#?
callbackis a global variable in the dll, so you can’t[1] set it from c#.You shouldn’t be setting it from C either. What you should have, if callback really is shared, is a function like
SetCallback( MyCallbackType callback )to set it.But probably, you want to pass the function to mainfunc.
In either case, this is easy to do in C#:
The take home message is that DllImport is smart enough to convert a delegate with a reasonably close signature to a C function pointer.
[1] Ok, so you can…dll injection sometimes uses one of a number of hacks along those lines, but it’s all kinds of the wrong way to do it in any other situation.