具有参数中的函数指针结构的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();