我有一些使用它的非托管C ++动态库和C#GUI应用程序。我想通过某些库提供的方法中的参数传递回调。是否可以从C#向非托管C ++方法传递回调。
// unmanaged C++
typedef uint8_t (__stdcall *SomeCallback)();
MYDLL_API uint8_t someMethod(SomeCallback cb);
我正在尝试以这种方式使用库:
// C# part
public delegate Byte SomeDelegate();
[DllImport("mylibraryname.dll")]
public static extern Byte someMethod(ref SomeDelegate pDelegate);
// actuak callback
Byte myCallback() {
// some code
}
...
// call unmanaged passing callback
static void Main(string[] args) {
someMethod(myCallback);
}
我收到编译错误:
cannot convert from 'method group' to 'ref SomeDelegate
我的方法完全错误吗?
这是因为您必须将ref
修饰符放在参数之前,并且将其强制为变量。所以:
将您的外部更改为:
public static extern Byte someMethod([MarshalAs(UnmanagedType.FunctionPtr)]
ref SomeDelegate pDelegate);
并致电给:
SomeDelegate action = new SomeDelegate(myCallback);
someMethod(ref action);
更新:如果您想将参数传递给回调(例如int):
public delegate Byte SomeDelegate([MarshalAs(UnmanagedType.I4)] int value);
[DllImport("mylibraryname.dll")]
public static extern Byte someMethod([MarshalAs(UnmanagedType.FunctionPtr)]
ref SomeDelegate pDelegate);
Byte MyMethod([MarshalAs(UnmanagedType.I4)] int value)
{
return (byte) (value & 0xFF);
}
并致电:
SomeDelegate action = new SomeDelegate(MyMethod);
someMethod(ref action);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句