I have a unmanaged C++ function with the following signature:
int function(char* param, int ret)
I am trying to call it from C#:
unsafe delegate int MyFunc(char* param, int ret);
…
int Module = LoadLibrary("fullpathToUnamanagedDll");
IntPtr pProc = GetProcAddress(Module, "functionName");
MyFunc func = (MyFunc)System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(pProc, typeof(MyFunc));
unsafe
{
char* param = null;
int ret = 0;
int result = func(param, ret);
}
As far as I can tell from the old C++ project specification both null for param and 0 for ret are valid inputs to the function. When I try to call it it seems to work, however upon exiting I get the following error:
PInvokeStackImbalance was detected
A call to PInvoke function
‘…::Invoke’
has unbalanced the stack. This is
likely because the managed PInvoke
signature does not match the unmanaged
target signature. Check that the
calling convention and parameters of
the PInvoke signature match the target
unmanaged signature.
I have tried pretty much anything I could think off (unsafe was last resort), however I can’t find any way to run the function without getting unbalanced stack. Is there something else I could try?
IIRC, you need to decorate the delegate signature with a calling convention. Unfortunately, this can only be done via IL or generating the stub with Reflection.Emit.
You can try this: