[英]C++ dll Pinvoke function with function pointer struct in parameter
我正在處理使用 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.