无法封送类型,因为嵌入式数组实例的长度与布局中声明的长度不匹配

Type could not be marshaled because the length of an embedded array instance does not match the declared length in the layout

这些是我的结构

[StructLayout(LayoutKind.Sequential)]
public struct DeptDetails
{
    [MarshalAs(UnmanagedType.I4)]
    public int depid;
    [MarshalAs(UnmanagedType.I2)]
    public short noemp;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
    public empDetails[] emp;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
    public string deptname;
}

[StructLayout(LayoutKind.Sequential)]
public struct empDetails
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
    public string empname;
    [MarshalAs(UnmanagedType.I4)]
    public int empid;
}

我通过套接字发送它

structures.DeptDetails Details = new structures.DeptDetails();
Details.depid = 123;
Details.noemp= 3;
Details.emp= new structures.empDetails[Details.noemp];

Details.emp[0].empname= "xyz"; 
Details.emp[0].empid= 1;

Details.scrips[1].empname="abc"
Details.scrips[1].empid = 2;

Details.scrips[2].empname= "pqr"
Details.scrips[2].empid= 6;

Details.deptname= "PYTHON";
int bytesSend = senderSock.Send(MainModule.struc.StructureToByteArray(Details));

StructureToByteArray 方法包含:

public byte[] StructureToByteArray(object obj)
{
    int len = Marshal.SizeOf(obj);
    byte[] arr = new byte[len];
    IntPtr ptr = Marshal.AllocHGlobal(len);
    Marshal.StructureToPtr(obj, ptr, true);
    Marshal.Copy(ptr, arr, 0, len);
    Marshal.FreeHGlobal(ptr);
    return arr;
}

但是我无法发送数据... 我的例外是:

Type could not be marshaled because the length of an embedded array instance does not match the declared length in the layout.

异常很明显:

...the length of an embedded array instance does not match the declared length in the layout

因此,您实例化了一个与声明的大小不同的数组(声明为 8,实例化为 3),因此无法对其进行编组。