C#中对结构体sizeof或Marshal.SizeOf返回的字节大小问题!!

龙宜坡 2008-11-21 03:35:53

//以下三个结构

public struct myStruct
{
public long lval;
public int ival;
}

public struct myStruct1
{
public long lval;
public int ival;
public string str;
}

public struct myStruct2
{
public long lval;
public int ival;
public object obj;
}

public struct myStruct3
{
public long lval;
public int ival;
public string str;
public object obj;
}

class Program
{
static void Main(string[] args)
{
int size;
size = sizeof(int);//返回4
Console.WriteLine("int 型变量占用" + size.ToString() + "字节");
size = sizeof(long);//返回8
Console.WriteLine("long 型变量占用" + size.ToString() + "字节");
unsafe
{
size = sizeof(myStruct); //据说是存在 字节对齐,所以结果为16
}
Console.WriteLine("myStruct 型变量占用" + size.ToString() + "字节");

//Marshal.SizeOf 获取已封送处理类型后的大小,而sizeof返回CLR分配的大小

size = System.Runtime.InteropServices.Marshal.SizeOf(new myStruct());//返回16,why?
Console.WriteLine("Marshal.SizeOf方法获得的myStruct占用" + size + "字节");

//why1??????????????
size = System.Runtime.InteropServices.Marshal.SizeOf(new mySturct1()); //返回16
Console.WriteLine("Marshal.SizeOf方法获得的myStruct1占用" + size + "字节");

//why2??????????????????
size = System.Runtime.InteropServices.Marshal.SizeOf(new mySturct2()); //返回16
Console.WriteLine("Marshal.SizeOf方法获得的myStruct2占用" + size + "字节");

//why3??????????????????
size = System.Runtime.InteropServices.Marshal.SizeOf(new mySturct3()); //返回24
Console.WriteLine("Marshal.SizeOf方法获得的myStruct3占用" + size + "字节");

Console.ReadKey();
}
}


问题:为什么why1,why2处返回为16,而why3处返回为24??谢谢!(.NET Framework 3.5)
...全文
2882 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
rosekin 2012-02-29
  • 打赏
  • 举报
回复
结尾工作:结构体的大小,也就是 sizeof 的结果必须是其内部最大成员的整数倍,不足的要补齐。 即这里必须是8 的倍数[Quote=引用 6 楼 fufengnudt 的回复:]

那也应该只是20呀
[/Quote]
fufengnudt 2011-07-25
  • 打赏
  • 举报
回复
那也应该只是20呀
cgp2008 2011-07-11
  • 打赏
  • 举报
回复
了解一下 哎
龙宜坡 2008-11-21
  • 打赏
  • 举报
回复
豁然开朗,谢谢!
gomoku 2008-11-21
  • 打赏
  • 举报
回复

struct3
------------
long : 8
int : 4
string : 4
object : 4
------------
超过16了。
龙宜坡 2008-11-21
  • 打赏
  • 举报
回复
先谢谢你的回答!
内存对齐我在网上搜了相关文章,有一点了解!

我的问题是
针对这样三个结构:

public struct myStruct1
{
public long lval;
public int ival;
public string str;
}//Marshal.SizeOf返回16

public struct myStruct2
{
public long lval;
public int ival;
public object obj;
}//Marshal.SizeOf依然返回16

public struct myStruct3
{
public long lval;
public int ival;
public string str;
public object obj;
}//关键这里,为什么一下子成了24了,按上面两个的结果看应该也是16才对,为什么呢?


使用Marshal.SizeOf方法后返回的结果怎么是16,16,24
gomoku 2008-11-21
  • 打赏
  • 举报
回复
现代的处理器架构对已经对齐的内存效率较高。
具体你可参考另一个帖子中的讨论:

新手问:内存对齐方式

111,097

社区成员

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

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

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