在只包含值类型的自定义结构使用Marshal.SizeOf()方法自定义、类型、结构、方法

2023-09-04 00:21:52 作者:仰 望 幸 富 ˇ

我创建了一个简单的结构它包含两个值类型。

 公共结构标识
{
    公众的Guid ID {获得;组; }
    公共字节请求类型{获取;组; }
}
 

然后我叫 Marshal.SizeOf()在自定义的结构方法标识符使用下面的语句。

 标识为i =新标识();
Console.WriteLine(Marshal.SizeOf(ⅰ)); //输出:20
Console.WriteLine(Marshal.SizeOf(i.GetType())); //输出:20
 

为什么 Marshal.SizeOf()不回17? 以下说明显示,的Guid 对象为16字节,一个字节对象 1个字节。

 的Guid G = Guid.NewGuid();
Console.WriteLine(Marshal.SizeOf(G)); //输出:16
Console.WriteLine(Marshal.SizeOf(g.GetType())); //输出:16

字节吨= 0;
Console.WriteLine(Marshal.SizeOf(吨)); //输出:1
Console.WriteLine(Marshal.SizeOf(t.GetType())); //输出:1
 
angular中自定义模块的构造与使用

解决方案

默认情况下,CLR被允许重新排列(这对于简单的结构就不可能发生)和垫结构,因为它为所欲为。这通常是当保持它对准字边界在存储器

如果你不喜欢这种行为,并想改变它,你可以按如下指定无包装:

  [StructLayout(LayoutKind.Sequential,包= 1)]
 

I created a simple struct which consists of two value types.

public struct Identifier
{
    public Guid ID { get; set; }
    public Byte RequestType { get; set; }
}

Then I called Marshal.SizeOf() method on the custom struct Identifier using the following statements.

Identifier i = new Identifier();
Console.WriteLine(Marshal.SizeOf(i));   // output: 20
Console.WriteLine(Marshal.SizeOf(i.GetType()));   // output: 20

Why does Marshal.SizeOf() not return 17? The following instructions show that a Guid object is 16 bytes and a Byte object is 1 byte.

Guid g = Guid.NewGuid();
Console.WriteLine(Marshal.SizeOf(g));   // output: 16
Console.WriteLine(Marshal.SizeOf(g.GetType()));   // output: 16

Byte t = 0;
Console.WriteLine(Marshal.SizeOf(t));   // output: 1
Console.WriteLine(Marshal.SizeOf(t.GetType()));   // output: 1

解决方案

By default the CLR is allowed to rearrange (which for simple structs it never does) and pad structs as it pleases. This is typically to keep it aligned to word boundaries when in memory.

If you don't like this behavior and want to change it, you can specify no packing as follows:

[StructLayout(LayoutKind.Sequential,Pack=1)]