现我有一个结构struct a
{
string str;
int i;
float f;
}
我希望这个结构是定长的,也就是说,str我希望是20个字节+4+8=32个字节,但是string是存的内存地址,肯定不对,所以打算改成char[],但char[]如何在结构中定义长度?
{
string str;
int i;
float f;
}
我希望这个结构是定长的,也就是说,str我希望是20个字节+4+8=32个字节,但是string是存的内存地址,肯定不对,所以打算改成char[],但char[]如何在结构中定义长度?
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
struct a
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
public char[] ch;
public int i;
public float f;
}class MyClass
{
public static void Main()
{
a s1;
s1.ch = null;
s1.i = 1;
s1.f = 1;
Console.WriteLine(Marshal.SizeOf(s1));
}
}
这样就可以了,输出是1032=512*2 + 4 + 4。希望这个对你有帮助。