c# - 结构大小未反射(reflect) C# 中的正确字节数

标签 c# pinvoke marshalling sizeof

我有一个结构定义如下:

public struct champ
{
    public uint mem1;
    public byte[] mem2;

    public champ(int x)
    {
        mem1 = x;
        mem2 = new byte[15];
    }
}

创建对象之后

champ sample = new champ (2);

应用 Marshal.SizeOf(sample) 返回 4+4 = 8 而不是 4 +15。为什么?

如果它是一个类,我能理解这个逻辑,因为第二个成员是一个占用 4 个字节的指针,它指向堆上的字节数组 mem2。为什么结构会发生这种情况?

最佳答案

mem2 字段没有 MarshalAs 属性,因此使用默认编码。这是指向第一个元素的指针。

你可能打算写:

public struct champ
{
    public uint mem1;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 15)]
    public byte[] mem2;

    public champ(int x)  { ... }
}

结构的大小将为 20,因为对齐规则意味着在结构的末尾添加了一个额外的填充字节。这需要确保结构的大小是 4 的精确倍数,即 uint 的大小。这确保结构的数组将正确对齐 mem1

关于c# - 结构大小未反射(reflect) C# 中的正确字节数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20148969/

相关文章:

c# - 抽象类中的抽象属性。重点是什么?

c# - 在 C# 中拆分 URL?

C# - 将不安全的 byte* 转换为 byte[]

c# - 如何使用 .NET P/调用 CryptUIWizExport 函数

c# - C# 中的等效 char*

c# - 为什么要插入倍数?

c# - ComboBox C# 中的默认值 DataSource

c++ - 从 C++/Win32 DLL 中 P/调用函数时获取 AccessViolationException

json - 在Grails中测试CustomObject编码器?

c# - 以更人性化的方式编码 char**