我想我基本上已经理解了如何为回调编写c#delegates,但是这个让我很困惑.c ++定义如下:
typedef int (__stdcall* Callback)(
long lCode,
long lParamSize,
void* pParam
);
Run Code Online (Sandbox Code Playgroud)
我的c#方法是:
unsafe delegate int CallbackDelegate (int lCode, int lParamSize, IntPtr pParam);
Run Code Online (Sandbox Code Playgroud)
虽然这似乎是不正确的,因为我得到一个PInvokeStackInbalance错误,这意味着我对委托的定义是错误的.
函数的其余参数是字符串或整数,这意味着它们不会导致错误,如果我只是传递一个IntPtr.Zero而不是委托(这意味着我指向一个不存在的回调函数)我得到一个AccessViolation错误,这也是有意义的.
我究竟做错了什么?
编辑:
完整的c ++功能是:
int
__stdcall
_Initialize (
const char* FileName,
Callback cbFunction,
int Code,
const char* Name,
unsigned int Option,
unsigned int Option2
);
Run Code Online (Sandbox Code Playgroud)
我的c#版本是:
[DllImport("MyDll.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int _Initialize (string FileName, CallbackDelegate cbFunction, int Code, string Name, uint Options, uint Options2);
Run Code Online (Sandbox Code Playgroud)
该函数是(用于测试)刚刚在控制台应用程序的主例程中调用:
static void Main(string[] args)
{
CallbackDelegate …Run Code Online (Sandbox Code Playgroud)