微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

具有参数中的函数指针结构的C ++ dll Pinvoke函数

如何解决具有参数中的函数指针结构的C ++ dll Pinvoke函数

我正在研究使用C ++ dll的C#代码
C ++ dll的一个函数在参数中包含3个函数指针的结构,我不知道如何管理它的任何提示主题
我尝试了这个,但这不起作用:

[StructLayout(LayoutKind.Sequential)]
public class displayCallBacks
{
    [MarshalAs(UnmanagedType.FunctionPtr)] initProgressBar ();                              
    [MarshalAs(UnmanagedType.FunctionPtr)] logMessage (int msgType,[MarshalAs(UnmanagedType.LPCWStr)] String str);
    [MarshalAs(UnmanagedType.FunctionPtr)] loadBar (int x,int n);                          
}

[DllImport("CubeProgrammer_API.dll",CallingConvention = CallingConvention.Cdecl,EntryPoint = "setdisplayCallbacks")]
internal static extern void SetdisplayCallbacks(displayCallBacks c);

C ++原型:

typedef struct displayCallBacks
{
    void (*initProgressBar)();                             
    void (*logMessage)(int msgType,const wchar_t* str); 
    void (*loadBar)(int x,int n);                        
} displayCallBacks;

void setdisplayCallbacks(displayCallBacks c);

解决方法

使用IntPtr作为函数指针的类型。 然后,您可以声明一个委托。这是我编写的代码示例:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate void PrintLogDelegate(string msg);

PrintLogDelegate pld;
System.Runtime.InteropServices.GCHandle callbackPrintLog;
IntPtr ipCBPrintLog = IntPtr.Zero;

pld = new PrintLogDelegate(PrintLogFunc);
callbackPrintLog = System.Runtime.InteropServices.GCHandle.Alloc(pld);
ipCBPrintLog = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(pld);


void PrintLogFunc(string msg)
{

}

ipCBPrintLog是您作为回调传递给C ++的内容。

然后在您的Dispose中进行清理:callbackPrintLog.Free();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。