在结构定义中初始化
struct Test
{
   int iflag;
   char address[256] = new char[256];
}

解决方案 »

  1.   

    谢谢,
    To  win32c(win32c):定义到外面,恐怕不行。To GiantHard(超级老虎邹):在结构定义中初始化,好像行不通。
      

  2.   

    下面这个结构实现了你需要的功能,GetByteCount()返回字节数,GetBytes()返回字节数组,字节数组第4位后面的字节是address变量指向的字符数组的值的字节流。
    [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]  
    public  struct Test
    {
    public int iflag;
    public char[] address;
    public int GetByteCount()
    {
    unsafe
    {
    int length=sizeof(int);
    int onechar=sizeof(char);
    if (address!=null)
    return length+=onechar*this.address.Length;
    else
    return length;
    }
    }
    public byte[] GetBytes()
    {
    unsafe
    {
    int length=this.GetByteCount();
    byte[] b=new byte[length];
    byte *pb;
    fixed (int *p=&iflag)
    pb=(byte *)p;
    for (int i=0;i<4;i++)
    {
    b[i]=*pb++;
    }
    if (address!=null)
    {
    fixed (char *p=address)
    pb=(byte *)p;
    for (int i=4;i<length;i++)
    {
    b[i]=*pb++;
    }
    }
    return b;
    }
    }
    }为什么不能使用sizeof来取得结构的大小,下面是C# Language Specification的规定:
    The sizeof operator returns the number of bytes occupied by a variable of a given type. The type specified as an operand to sizeof must be an unmanaged-type (§25.2). 
    sizeof-expression : 
    sizeof ( unmanaged-type ) An unmanaged-type is any type that isn't a reference-type and doesn't contain reference-type fields at any level of nesting. 
    In other words, an unmanaged-type is one of the following: 
    sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool. 
    Any enum-type. 
    Any pointer-type. 
    Any user-defined struct-type that contains fields of unmanaged-types only.  \\\|///
          \\ .-.- //
    .      ( .@.@ )
    o00-------oOOo-----(_)-----oOOo---------0o
    |                  |
    |  新年快乐!!!  |
    |                  |
    0o0oo---------------------Oooo----------o0oo
      

  3.   

    直接分配内存即可,无须sizeof!