我正在尝试将结构从 C# 传递到 C++ 库。我将结构作为对象传递,C++ 函数期望它作为指针 (void *)。
我在传递结构时遇到问题。
[DllImport("MockVadavLib.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr TheFunction([MarshalAs(UnmanagedType.LPStruct)] UserRec userRec);
这是我得到的运行时异常文本:
"Cannot marshal 'parameter #1': Invalid managed/unmanaged type combination (this value type must be paired with Struct)."
尽管我发现了一篇 MSDN 文章正是在这种情况下使用 LPStruct。
这是我要整理的结构:
[StructLayout(LayoutKind.Sequential)]
public struct UserRec {
[MarshalAs(UnmanagedType.I4)]
public int userParam1;
}
这是 C++ 函数:
MOCKVADAVLIB_API tVDACQ_CallBackRec * TheFunction(void * userParams) {...
最佳答案
尝试将结构作为 ref 参数传递。
[DllImport("MockVadavLib.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr TheFunction(ref UserRec userRec);
当您将 ref 与结构结合使用时,它在概念上传递了地址。
关于c# - 如何将结构编码为指向结构的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/827672/