菜鸟纳闷:byte与ushort 问题,见笑了 呵呵

new_yang 2012-09-18 10:51:39
情况如下:
public struc aa
{
public byte a;
public ushort b;
}

测试:
click:
ushort Len;
aa a = new aa();
Len=(ushort)Marshal.SizeOf(a);// 这里len=4 bytes (按道理应该是3bytes啊 不知道为什么,大侠能否解释下?)

************************************
public struc aa
{
//public byte a;
public ushort b;
}

测试:
click:
ushort Len;
aa a = new aa();
Len=(ushort)Marshal.SizeOf(a);// 这里len=2 bytes (这里没错)
***************************
public struc aa
{
public byte a;
// public ushort b;
}

测试:
click:
ushort Len;
aa a = new aa();
Len=(ushort)Marshal.SizeOf(a);// 这里len=1 byte(这里没错)

************************
byte,ushort 组合 就出现了问题,难道是Marshal.SizeOf这个函数不可靠? 求解释
...全文
224 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
new_yang 2012-09-18
  • 打赏
  • 举报
回复
谢谢
宝_爸 2012-09-18
  • 打赏
  • 举报
回复
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)]

以上来自:
Using Marshal.SizeOf() method on a custom struct containing only value types
http://stackoverflow.com/questions/9220999/using-marshal-sizeof-method-on-a-custom-struct-containing-only-value-types
SocketUpEx 2012-09-18
  • 打赏
  • 举报
回复
大概要加上[StructLayout(LayoutKind.Sequential, Pack = 1)]


宝_爸 2012-09-18
  • 打赏
  • 举报
回复
应该是4字节对齐了。
bdmh 2012-09-18
  • 打赏
  • 举报
回复
字节对齐问题

110,825

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧