c++结构:
struct Block
{
unsigned char a[8];
unit16 index1;
unit16 index2;
uint32 flag;
};
在c#中出现错误:"结构中不能有实例字段初始值设定项".
我写成c#后变这样:
struct Block
{
public Block(int i)
{
a = new byte[8];
Indices1 = 0;
Indices2 = 0;
bitmask = 0;
}
byte[] a;
unit16 index1;
unit16 index2;
uint32 flag;
};
虽然能编译了,但是当我用int size = Marshal.SizeOf(structObj);来取字节数的时候读出size值是12,结构应该是16,如何才能正确读到size值?
struct Block
{
unsigned char a[8];
unit16 index1;
unit16 index2;
uint32 flag;
};
在c#中出现错误:"结构中不能有实例字段初始值设定项".
我写成c#后变这样:
struct Block
{
public Block(int i)
{
a = new byte[8];
Indices1 = 0;
Indices2 = 0;
bitmask = 0;
}
byte[] a;
unit16 index1;
unit16 index2;
uint32 flag;
};
虽然能编译了,但是当我用int size = Marshal.SizeOf(structObj);来取字节数的时候读出size值是12,结构应该是16,如何才能正确读到size值?
unit16 index1;
unit16 index2;
uint32 flag;
是16个字节
{
public Block(int i) //i?
{
a = new byte[8];
Indices1 = 0;
Indices2 = 0;
bitmask = 0; //bitmask?=>flag?!
}
byte[] a;
uint16 index1;
uint16 index2;
uint flag;
}; 试下
byte[] a
这个其实是一个引用
Block block=new Block(i);
int size = Marshal.SizeOf(block);这里返回的size值不对啊,应该返回16才对
{
a = new byte[8]{0};
Indices1 = 0;
Indices2 = 0;
bitmask = 0;
}
unsafe struct Block
{
[StructLayout(LayoutKind.Sequential, Size = 8)]
public struct aAtruct
{
public byte this[int index]
{
get
{
fixed (aAtruct* aptr = &this)
{
byte* ptr = (byte*)aptr;
return ptr[index];
}
}
}
}
public aAtruct a;
public ushort index1;
public ushort index2;
public uint flag;
}unsafe struct Block2
{
[MarshalAs(UnmanagedType.ByValArray)]
public byte[] a;
public ushort index1;
public ushort index2;
public uint flag;
}
{
public Block()
{
a1=a2=.a3.. =a8=0;
Indices1 = 0;
Indices2 = 0;
bitmask = 0;
}
byte a1,a2,a3...a8;
unit16 index1;
unit16 index2;
uint32 flag; 这样就是16了
unsafe struct Block2
{
[MarshalAs(UnmanagedType.ByValArray,SizeConst=8)]
public byte[] a;
public ushort index1;
public ushort index2;
public uint flag;
}
还可以这样写:
unsafe struct Block2
{
public fixed byte a[8];
public ushort index1;
public ushort index2;
public uint flag;
}使用起来有些区别的。12楼的写法是托管类型的,这种是非托管类型的,可以进行指针运算