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值?

解决方案 »

  1.   

    unsigned char a[8];
    unit16 index1;
    unit16 index2;
    uint32 flag; 
    是16个字节
      

  2.   

    struct Block 

            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;
     
    }; 试下
      

  3.   

    其实程序里面你应该看出来了
    byte[] a
    这个其实是一个引用
      

  4.   

    这个办法我用了,下面
    Block block=new Block(i);
    int size = Marshal.SizeOf(block);这里返回的size值不对啊,应该返回16才对
      

  5.   

    因为你并没有给a = new byte[8]分配实际的空间,此时A只不过是个指针 32位就是4 字节,加上余下的2个uint16和一个uint32就是12字节
      

  6.   

    public Block(int i) 
            { 
                a = new byte[8]{0}; 
                Indices1 = 0; 
                Indices2 = 0; 
                bitmask = 0; 
            } 
      

  7.   

    两种写法,任选一种,第一种写法的好处是可以把C#结构体和C++结构体等同起来,内存空间上是连续的,第二种的写法是C#标准写法,但是:::无法象C++那样进行结构体处理,推荐第一种写法
    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;
    }
      

  8.   

    struct Block 

            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了
      

  9.   

    修改一下第二种写法
    unsafe struct Block2
    {
    [MarshalAs(UnmanagedType.ByValArray,SizeConst=8)]
    public byte[] a;
    public ushort index1;
    public ushort index2;
    public uint flag;
    }
      

  10.   

    12楼的写法不用unsafe。
    还可以这样写:
    unsafe struct Block2
    {
        public fixed byte a[8];
        public ushort index1;
        public ushort index2;
        public uint flag;
    }使用起来有些区别的。12楼的写法是托管类型的,这种是非托管类型的,可以进行指针运算
      

  11.   

    10楼的第一种写法用public fixed byte a[8]; 代替更简洁