将struct类型的固定大小数组作为另一个struct的成员

将struct类型的固定大小数组作为另一个struct的成员

问题描述:

大家好!

我必须通过TCP/IP从旧服务器发送和接收数据.我发送和接收的字节当然代表了一些数据结构.在C/C ++中,我会将数组存储到现有结构中,或者将strcut类型的指针转​​换为我的字节数组.在C中看起来像这样:

Hi folks!

I have to send and receive data via TCP/IP from a legacy server. The bytes I send and receive are of course representing some data structures. In C/C++ I would memcpy the array into an existing structure or I would just cast a pointer of the strcut type to my byte array. In C it would look something like this:

#pragma pack(push, 1)

typedef struct INNER_ST
{
    DWORD A;
    BYTE B;
};

typedef struct FOO_ST
{
    WORD W;
    BYTE X[20];
    INNER_ST data[10];
};

#pragma pack(pop, 1)

void ReceiveData(const BYTE *pData)
{
    FOO_ST *pFooSt;

    pFooSt = (FOO_ST *)pData;

    DWORD alpha = pFooSt->data[0].A;

}




在C#中,我的结构如下所示:




In C# my structures would look like this:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct INNER_ST
{
    public UInt32 A;
    public Byte B;
};

[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct FOO_ST
{
    public UInt16 W;
    public fixed Byte X[20];
    public fixed INNER_ST data[10]; // <- fails, Error CS1663 
    /*
    "Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double"
    */
};



用Marshal.PtrToStructure复制像INNER_ST这样的简单"结构不是问题.

我的问题:如何处理结构内部的结构数组以解决错误CS1663.

感谢任何想法或提示.
安迪

PS:当然,我不能更改服务器端.我在C中有带有结构定义的头文件,新的客户端将在C#中.



To copy "simmple" structures like INNER_ST with Marshal.PtrToStructure is not the problem.

My question: What can I do with arrays of structures inside structure to solve error CS1663.

Thx for any ideas or hints.
Andy

PS: Of course I cannot change the server side. I have the header files with the structure definitions in C and the new client will be in C#.

忽略我以前发布的内容,我在某种程度上使事情变得过于复杂了!当需要将未知长度的数据进行编组时,可以使用我建议的方法.

如您所知,它很简单:
Ignore what I posted previously, I was somewhat overcomplicating things! The method I suggested can be used when an unknown length of data is required to be marshalled.

As you know the length, it''s simple:
[StructLayout(LayoutKind.Sequential)]
struct Inner
{
    public uint A;
    public byte B;
}


[StructLayout(LayoutKind.Sequential)]
struct Foo
{
    public ushort W;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
    public byte[] X;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public Inner[] data;
}


为什么要使用fixedunsafe?


Why are you using fixed and unsafe?