【问题标题】:C++ dll Pinvoke function with function pointer struct in parameterC ++ dll Pinvoke函数,参数中有函数指针结构
【发布时间】:2021-02-19 06:42:06
【问题描述】:

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

【问题讨论】:

  • 没有看到 c++ 原型就无法判断。您应该使用结构而不是类来与 c++ 相同。
  • 我添加了 C++ 原型
  • 一个问题是DisplayCallbacks 中的所有方法都没有任何返回类型
  • 您需要定义ProgressBar、logMessage、Bar这三种类型,并为每种类型分配正确的内存量。 c++ 代码结构是 12 个字节,因为每个指针是 4 个字节。因此,非托管内存中的结构以及 3 个对象的非托管内存需要 12 个字节。
  • 定义三种类型是什么意思?声明函数?

标签: c# c++ pinvoke


【解决方案1】:

使用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();

【讨论】:

    猜你喜欢
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多