如何将结构编组为指向结构的指针?
我正在尝试将结构从 C# 传递到 C++ 库。 我将结构作为对象传递,C++ 函数期望它作为指针 (void *)。
我在传递结构时遇到问题。
[DllImport("MockVadavLib.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr TheFunction([MarshalAs(UnmanagedType.LPStruct)] UserRec userRec);
这是我得到的运行时异常文本:
“无法封送‘参数 #1’:托管/非托管类型组合无效(此值类型必须与 Struct 配对)。”
尽管我发现一篇 MSDN 文章正是在这种情况下使用 LPStruct。
这是我正在尝试编组的结构:
[StructLayout(LayoutKind.Sequential)]
public struct UserRec {
[MarshalAs(UnmanagedType.I4)]
public int userParam1;
}
这是 C++ 函数:
MOCKVADAVLIB_API tVDACQ_CallBackRec * TheFunction(void * userParams) {...
I am trying to pass a structure from C# into C++ library. I pass structure as an object, and C++ function expects it as a pointer (void *).
I am having problem passing the structure.
[DllImport("MockVadavLib.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr TheFunction([MarshalAs(UnmanagedType.LPStruct)] UserRec userRec);
Here is the run-time exception text I get:
"Cannot marshal 'parameter #1': Invalid managed/unmanaged type combination (this value type must be paired with Struct)."
Though I found an MSDN article that uses LPStruct in exactly this context.
This is my structure I'm trying to marshal:
[StructLayout(LayoutKind.Sequential)]
public struct UserRec {
[MarshalAs(UnmanagedType.I4)]
public int userParam1;
}
This is C++ function:
MOCKVADAVLIB_API tVDACQ_CallBackRec * TheFunction(void * userParams) {...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
顺便说一句,
UnmanagedType.LPStruct
很少(如果有的话)是正确的MarshalAs
参数。 引用来自 Microsoft 员工 Adam Nathan员工:Incidentally,
UnmanagedType.LPStruct
is rarely, if ever, the correctMarshalAs
argument. A quote from Adam Nathan who is a Microsoft employee:尝试将该结构作为 ref 参数传递。
当您将 ref 与结构结合使用时,它在概念上传递地址。
Try passing the structure as a ref parameter.
When you use a ref combined with a structure, it conceptually passes the address.
关于@Rytmis 帖子的一些附加信息后续。
来自 https://learn.microsoft.com /en-us/dotnet/standard/native-interop/best-practices#guid:
Some additional information followup regarding @Rytmis's post.
From https://learn.microsoft.com/en-us/dotnet/standard/native-interop/best-practices#guids: