13

我想在我的 c# 代码中访问这个函数,这可能吗?所以最后 c++ 代码会调用我的函数并应用名为“sFrameofData”的结构。

C++ 代码:

//The user supplied function will be called whenever a frame of data arrives.
DLL int Cortex_SetDataHandlerFunc(void (*MyFunction)(sFrameOfData* pFrameOfData));

这可能行得通吗?

C#代码:

[DllImport("Cortex_SDK.dll")]
public extern static int Cortex_SetDataHandlerFunc(ref IntPtr function(ref IntPtr pFrameOfData) );
4

2 回答 2

33

您想使用与“MyFunction”C++ 方法的方法签名相匹配的委托。

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void MyFunctionDelegate(IntPtr frame);

[DllImport("Cortex_SDK.dll")]
public extern static int Cortex_SetDataHandlerFunc(
[MarshalAs(UnmanagedType.FunctionPtr)]MyFunctionDelegate functionCallback);
于 2011-03-08T16:48:20.730 回答
1

我不确定什么是正确的方法,但我认为将 ref IntPtr 用于函数和结构还不够......

请参阅此处获取帮助:C# P/Invoke: Marshalling structure contains function pointers

于 2011-03-08T16:50:51.497 回答