UnmanagedType.LPArray in structure

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mrvetal
    New Member
    • May 2011
    • 1

    UnmanagedType.LPArray in structure

    Hello

    My programm receives array of bytes over SSL from Delphi program.
    I convert it into structure and have en error:
    Type 'SetOrder' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed

    Delphi:
    Code:
    TTLVHADPrefix = packed record
      ProtocolID: TProtocolID;
      Version: Byte;
    end;
    Code:
    TTLVHAD = packed record
      Prefix: TTLVHADPrefix;
      Len: DWORD;
      TermID: TTermID;
      OperCode: WORD;
    end;
    Code:
    TTLV602 = packed record
      Header: TTLVHAD;
     [B][U] AccNumLen: WORD;
      AccNum: array of Char;[/U][/B]
      AccType: Char;
      Status: Char;
    end;

    My C#

    Code:
            [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
            public struct TlvHad
            {
                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
                public Char[] tlv;          
                public Byte protocolVer; 
            }
    Code:
            [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
            public struct HeaderQry
            {
                public TlvHad prefix; 
                public UInt32 len;
                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
                public Char[] termID; 
                public UInt16 operCode;
            }
    Code:
           [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
            public struct SetOrder
            {
                public HeaderQry headerQry; 
    [B][U]            public UInt16 AccNumLen;    
                [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=12)]
                public Char[] AccNum; [/U][/B]      
                public Char Type;           
                public Char Status;         
            }

    Code:
            public static object Deserialize(byte[] rawdatas, Type anytype)
            {
    [B][U]ERROR THIS[/U][/B]  int rawsize = Marshal.SizeOf(anytype);
                if (rawsize > rawdatas.Length)
                    return null;
                GCHandle handle = GCHandle.Alloc(rawdatas, GCHandleType.Pinned);
                IntPtr buffer = handle.AddrOfPinnedObject();
                object retobj = Marshal.PtrToStructure(buffer, anytype);
                handle.Free();
                return retobj;
            }
  • bvrwoo
    New Member
    • Aug 2011
    • 16

    #2
    I am not sure that you can marshal the size of anytype because you can only marshal structures I believe do the CLR reallocating the heap which you cannot control. Thus is the same reason you cannot use the fixed keyword on a class type to point to. In cases like this it is far better to use C++/CLI.

    Comment

    Working...