locked
Convert byte array to structure in the Compact Framework RRS feed

  • General discussion

  • I need to convert a byte array to my structure type. To do this I use the following code for desktop project application:

    var str = new SFHeader();
    int size = Marshal.SizeOf(str);
    
    IntPtr ptr = Marshal.AllocHGlobal(size);
    Marshal.Copy(buffer, 0, ptr, size);
    str = (SFHeader)Marshal.PtrToStructure(ptr, typeof(SFHeader));
    Marshal.FreeHGlobal(ptr);
    
    return str;

    Where SFHeader is my structure.

    The problem is that the line:

    str = (SFHeader)Marshal.PtrToStructure(ptr, typeof(SFHeader));

    throws a NotSupportedException when I run this code from a smart device project. Are there others methods to do this work in the Compact Framework?

    Friday, November 16, 2012 2:48 PM

All replies

  • AFAIK there are no other methods but this method should work assuming your structure is blittable and has proper attributes on it. 

    If you post your structure definition I may be able to spot the issue. 



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

    Friday, November 16, 2012 4:55 PM
  • AFAIK there are no other methods but this method should work assuming your structure is blittable and has proper attributes on it. 

    If you post your structure definition I may be able to spot the issue. 



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

    [StructLayout(LayoutKind.Sequential)]
    public struct SFHeader
    {
    
        internal const int MAX_FILENAME_LENGTH = 32;
    
    
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_FILENAME_LENGTH)]
        public string FileName;
    
        public int Offset;
    
        public short Size;
    
        public byte Flags;
    
        public byte Source;
    
        public long LastWriteTime;
    
    }

    Friday, November 16, 2012 7:28 PM
  • I don't see any problems with this, should work. Do you have a stack trace for the exception?

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

    Saturday, November 17, 2012 2:11 AM
  • Hi,

    According to your description, you issue may has not a solid answer; I think it should be better if we change the thread type to General Discussion.

    Thanks for your understanding and active participation in the MSDN Forum.
    Regards,


    Elegentin Xie
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, December 10, 2012 2:44 AM