我正在编写一个使用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();