Is there an alternative for StructLayout “Pack” attribute in Compact Framework? RRS feed

  • Question

  • I have the following structure:

    [StructLayout(LayoutKind.Sequential, Pack=1)]  // notice the packing here
    public struct SFHeader
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
        public string FileName;
        public int Offset;
        public short Size;
        public byte Flags;
        public byte Source;
        public long LastWriteTime;

    I need to use the same structure of 21 bytes, in a smart device project (i.e. without the Pack attribute).

    How can I do?

    • Edited by doh666 Monday, November 12, 2012 4:26 PM
    Monday, November 12, 2012 4:25 PM


  • You can specify explicit layout and place each field at specific offset. However since layout rules are rather restrictive on RISC CPUs that may fail. For example, 32 bit integer usually must be 4 byte aligned or CPU would throw data misaligned exception if they are not. 

    If you're using this structure for interop then you don't need to do anything as default layout should match native one.

    If you're using it for data exchange with another system then you probably would need to load data into the byte array and then manually extract data and fill data structure.

    Also your fields are totaling 5 * 2 + 4 + 2 + 1 +1 + 8 = 26 bytes. So it never would be 21 byte. If you meant to have 8 bit characters then you should declare FileName as byte array and do manual marshaling (remember CE is Unicode OS, all strings are always using 16 bit characters). 

    This posting is provided "AS IS" with no warranties, and confers no rights.

    • Marked as answer by doh666 Monday, November 12, 2012 9:22 PM
    Monday, November 12, 2012 5:36 PM