在只包含值类型的自定义结构使用Marshal.SizeOf()方法 [英] Using Marshal.SizeOf() method on a custom struct containing only value types

查看:94
本文介绍了在只包含值类型的自定义结构使用Marshal.SizeOf()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 公共结构标识
{
    公众的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
 

解决方案

默认情况下,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)]

这篇关于在只包含值类型的自定义结构使用Marshal.SizeOf()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆