简体   繁体   English

如何将结构编组为指向结构的指针?

[英]How do I marshal a structure as a pointer to a structure?

I am trying to pass a structure from C# into C++ library.我正在尝试将结构从 C# 传递到 C++ 库。 I pass structure as an object, and C++ function expects it as a pointer (void *).我将结构作为对象传递,而 C++ 函数将其作为指针(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)." “无法封送‘参数#1’:无效的托管/非托管类型组合(此值类型必须与 Struct 配对)。”

Though I found an MSDN article that uses LPStruct in exactly this context.尽管我发现了一篇 MSDN 文章,它正是在这种情况下使用了 LPStruct。

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:这是 C++ 函数:

MOCKVADAVLIB_API tVDACQ_CallBackRec * TheFunction(void * userParams) {...

Try passing the structure as a ref parameter.尝试将结构作为 ref 参数传递。

[DllImport("MockVadavLib.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr TheFunction(ref UserRec userRec);

When you use a ref combined with a structure, it conceptually passes the address.当您将 ref 与结构结合使用时,它在概念上会传递地址。

Incidentally, UnmanagedType.LPStruct is rarely, if ever, the correct MarshalAs argument.顺便说一句, UnmanagedType.LPStruct很少(如果有的话)是正确的MarshalAs参数。 A quote from Adam Nathan who is a Microsoft employee: 来自微软员工Adam Nathan 的一句话

UnmanagedType.LPStruct is only supported for one specific case: treating a System.Guid value type as an unmanaged GUID with an extra level of indirection. UnmanagedType.LPStruct 仅在一种特定情况下受支持:将 System.Guid 值类型视为具有额外间接级别的非托管 GUID。

Some additional information followup regarding @Rytmis's post.关于@Rytmis 帖子的一些附加信息跟进。

From https://docs.microsoft.com/en-us/dotnet/standard/native-interop/best-practices#guids :https://docs.microsoft.com/en-us/dotnet/standard/native-interop/best-practices#guids


DO NOT Use [MarshalAs(UnmanagedType.LPStruct)] for anything other than ref GUID parameters.不要将[MarshalAs(UnmanagedType.LPStruct)]用于除 ref GUID 参数以外的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM