[英]Size of struct C#
I'm new in C#. 我是C#的新手。
I'm trying to understand why the struct size is grow. 我试图理解为什么结构大小增长。
Ie: 即:
struct Test
{
float x;
int y;
char z;
}
size of Test struct is actually 10 bytes (float=4, int=4, char=2). Test结构的大小实际上是10个字节(float = 4,int = 4,char = 2)。
But when i tried to get the sizeof struct with Marshal.SizeOf(..)
method i got 12. 但是当我试图用Marshal.SizeOf(..)
方法得到sizeof结构时,我得到了12。
In C++ i did pragma pack(1)
to prevent this but how can i do it in C#? 在C ++中,我做了pragma pack(1)
来防止这种情况,但我怎么能用C#做呢?
Another question: 另一个问题:
When i tried to convert the Test struct to byte array if the struct isn't [Serialize]
i got byte array with size 12 bytes as excepted (or not), but if the struct is [Serialize]
i got byte array with size of 170 bytes, why its happend? 当我试图将Test结构转换为字节数组时,如果结构不是[Serialize]
我得到大小为12字节的字节数组作为例外(或不是),但如果结构是[Serialize]
我得到的字节数组大小为170字节,为什么会发生?
Thanks! 谢谢! :) :)
This 这个
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TestStruct
{
float x;
int y;
char z;
}
will give a Marshal.SizeOf() == 9
, because Marshal.SizeOf(typeof(char)) == 1
for strange historical reasons. 将给出Marshal.SizeOf() == 9
,因为Marshal.SizeOf(typeof(char)) == 1
出于奇怪的历史原因。
BUT 但
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
with this you'll get Marshal.SizeOf() == 10
有了它你就会得到Marshal.SizeOf() == 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.