PInvoke的C#:函数接受函数指针作为参数 [英] PInvoke C#: Function takes pointer to function as argument

查看:806
本文介绍了PInvoke的C#:函数接受函数指针作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的C#code访问此功能,这可能吗?所以最后的C ++ code会叫我的功能,也适用于被称为sFrameofData的结构。

C ++ code:

  //每当数据帧到达用户提供的函数将被调用。
DLL INT Cortex_SetDataHandlerFunc(无效(* MyFunction的)(sFrameOfData * pFrameOfData));

将这工作吧?

C#code:

 函数[DllImport(Cortex_SDK.dll)]
公众的extern静态INT Cortex_SetDataHandlerFunc(REF IntPtr的功能(REF IntPtr的pFrameOfData));


解决方案

您要使用你的MyFunction的C ++方法的方法签名匹配的委托。

  [UnmanagedFunctionPointer(CallingConvenction.Cdecl)
公共委托无效MyFunctionDelegate(IntPtr的帧);函数[DllImport(Cortex_SDK.dll)]
公众的extern静态INT Cortex_SetDataHandlerFunc(
[的MarshalAs(UnmanagedType.FunctionPtr)MyFunctionDelegate functionCallback);

I'd like to access this function in my c# code, is this possible? so in the end the c++ code would call my function and also apply the struct called "sFrameofData".

C++ Code:

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

Would this work perhaps?

C# Code:

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

解决方案

You want to use a delegate that matches the method signature of your "MyFunction" C++ method.

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

[DllImport("Cortex_SDK.dll")]
public extern static int Cortex_SetDataHandlerFunc(
[MarshalAs(UnmanagedType.FunctionPtr)]MyFunctionDelegate functionCallback);

这篇关于PInvoke的C#:函数接受函数指针作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆