Dav*_*jak 4 c# c++ unsafe unmanaged
我有一个带有以下签名的非托管C++函数:
int function(char* param, int ret)
Run Code Online (Sandbox Code Playgroud)
我试图用C#调用它:
unsafe delegate int MyFunc(char* param, int ret);
Run Code Online (Sandbox Code Playgroud)
...
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);
}
Run Code Online (Sandbox Code Playgroud)
据我所知,从旧的C++项目规范中,param为null ,ret为0 都是函数的有效输入.当我尝试调用它似乎工作,但退出时我得到以下错误:
检测到PInvokeStackImbalance
对PInvoke函数'... :: Invoke'的调用使堆栈失去平衡.这很可能是因为托管PInvoke签名与非托管目标签名不匹配.检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配.
我已经尝试了几乎任何我能想到的东西(不安全是最后的手段),但是我找不到任何方法来运行该函数而不会得到不平衡的堆栈.还有什么我可以尝试的吗?
我知道这个问题现在已经有一年了,但是比动态构建类型更简单的方法是使用UnmanagedFunctionPointer委托上的属性声明调用约定,如下所示:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
unsafe delegate int MyFunc(char* param, int ret);
Run Code Online (Sandbox Code Playgroud)
来自MSDN:
控制作为非托管函数指针传递给非托管代码或从非托管代码传递的委托签名的编组行为.