gpt4 book ai didi

c# - C++ dll Pinvoke函数,参数中有函数指针结构

转载 作者:行者123 更新时间:2023-12-03 07:22:28 25 4
gpt4 key购买 nike

我正在编写使用 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++ 原型(prototype):
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作为函数指针的类型。
然后你可以声明一个委托(delegate)。这是我编写的代码示例:

[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();

关于c# - C++ dll Pinvoke函数,参数中有函数指针结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64716180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com