gpt4 book ai didi

c# - 编码(marshal)结构后跟固定大小的数据

转载 作者:行者123 更新时间:2023-11-30 05:27:17 26 4
gpt4 key购买 nike

我想将一些数据从 C# 传递到 C++。这些数据由struct 和guid 组成。由于 guid 是类,我决定在结构数据之后立即复制它。有一个更好的方法吗?该解决方案有效,并且可以在 C++ 中正确读取数据,但我不太担心是否存在这种方法不起作用的情况。

结构:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TEST_STRUCT
{
public Uint32 var1;
public Uint32 var2;
}

使用:

TEST_STRUCT testStruct = new TEST_STRUCT(); // filled somewhere
byte [] guid; // defined above

IntPtr mem = Marshal.AllocHGlobal(Marshal.SizeOf(testStruct.GetType()) + guid.Length);
try
{
Marshal.StructureToPtr(testStruct, mem, false);
Marshal.Copy(guid, 0, new IntPtr(mem.ToInt64() + Marshal.SizeOf(testStruct.GetType())), guid.Length);

// send data to c++ ...
}
finally
{
Marshal.FreeHGlobal(mem);
}

最佳答案

在这种非常特殊的情况下,您会摆脱它,GUID 没有对齐要求。该结构始终为 24 字节长。

但这样做没有意义,pinvoke 编码器知道如何正确编码 System.Guid。它是一个值类型(结构),而不是您假设的类,并且它的内部结构故意笨拙,因此它与 native GUID 完全匹配。你可以从 Reference Source 中看到一些东西例如。这是非常有意的,Guid 在互操作中很重要,特别是 COM 代码大量使用它们。

所以只需要:

struct TEST_STRUCT
{
public Uint32 var1;
public Uint32 var2;
public Guid guid;
}

我特意省略了 [StructLayout] 属性,这是没有必要的,也不需要调整包装。

关于c# - 编码(marshal)结构后跟固定大小的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37463510/

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