[转]C和C# struct对齐
C#代码:
using System;
namespace ConsoleApplication
{
public unsafe struct TestStruct
{
public int x;
public int y;
public fixed byte cs[10];
public int z;
}
class Program
{
unsafe static void Main(string[] args)
{
TestStruct ts = new TestStruct()
{
x = 10
,
y = 20
,
z = 30
};
for (int i = 0; i < 10; i++)
{
*(ts.cs + i) = (byte)(i + 10);
}
byte[] bs = new byte[sizeof(TestStruct)];
for (int i = 0; i < sizeof(TestStruct); ++i)
{
bs[i] = *(((byte*)&ts) + i);
}
Console.WriteLine(string.Format("C# Data({0}):", sizeof(TestStruct)));
for (int i = 0; i < sizeof(TestStruct); ++i)
{
Console.Write(*(((byte*)&ts) + i));
Console.Write(" ");
}
Console.ReadLine();
}
}
}
C代码:
#include <stdio.h>
typedef struct
{
int x;
int y;
char cs[10];
int z;
} TestStruct;
int main()
{
TestStruct ts = { 0 };
ts.x = 10;
ts.y = 20;
ts.z = 30;
for (int i = 0; i < 10; ++i)
{
*(ts.cs + i) = i + 10;
}
printf(" C Data(%d):\n",sizeof(ts));
for (int i = 0; i < sizeof(ts); ++i)
{
printf("%d ", *((char*)&ts + i));
}
return 0;
}

浙公网安备 33010602011771号