使用结构数组时的元帅异常

时间:2012-03-29 08:30:43

标签: c# serialization struct marshalling

我收到以下错误:

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

在线 Marshal.StructureToPtr(msg,buff,true

public static Byte[] SerializeMessage<T>(T msg) where T : struct
{
     int objsize = Marshal.SizeOf(typeof(T));
     Byte[] ret = new Byte[objsize];
     IntPtr buff = Marshal.AllocHGlobal(objsize);
     Marshal.StructureToPtr(msg, buff, true);
     Marshal.Copy(buff, ret, 0, objsize);
     Marshal.FreeHGlobal(buff);
     return ret;
}

以下是我尝试使用的结构:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct MsgStruct
{
    public uint result;
    public DS.DataSvcMetZoneDataC zone;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 240)]
    public Types.GeographicLocationType[] geoLocation;
    static public MsgStruct NewMsgStruct()
    {
        MsgStruct retValue = new MsgStruct();
        retValue.geoLocation = new Types.GeographicLocationType[10];
        for (int i = 0; i < 10; i++)
        {
            retValue.geoLocation[i] = Types.GeographicLocationType.NewMsgStruct();
        }
       return retValue;
    }
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct GeographicLocationType
{
    public double altitude;
    public double latitude;
    public double longitude;
    static public GeographicLocationType NewMsgStruct()
    {
        GeographicLocationType structType = new GeographicLocationType();
        return structType;
    }
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct DataSvcMetZoneDataC
{
    public int metID;
    public ushort zoneNumber;
    public ushort isDefined;
    public double windDirection;
    public double windSpeed;
    public double airTemperature;
    public double airPressure;
    public ulong dataModifiedInd;
    static public DataSvcMetZoneDataC NewMsgStruct()
    {
        DataSvcMetZoneDataC structType = new DataSvcMetZoneDataC();
        return structType;
    }
}

当我没有一系列位置但是将它们命名为1时,我可以使用它....对于应该能够轻松使用数组的东西来说,10似乎是一个糟糕的解决方案。

0 个答案:

没有答案