簡體   English   中英

C++ dll Pinvoke 函數,參數中帶有函數指針結構

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM