简体   繁体   中英

Convert byte array to structure in the Compact Framework

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?

[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;

}

Marshal.PtrToStructure works and I've used it many times in the compact framework. it looks like you are using it correctly. Therefore, the problem must be your struct definition (something might not be supported in the CF for the struct)

The following code runs just fine on my device using Windows CE 5.0 and .NET CF 3.5

[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;
    }

    private static void Test()
    {
        var str = new SFHeader();
        int size = Marshal.SizeOf(str);
        byte[] buffer = new byte[size];

        IntPtr ptr = Marshal.AllocHGlobal(size);
        Marshal.Copy(buffer, 0, ptr, size);
        str = (SFHeader)Marshal.PtrToStructure(ptr, typeof(SFHeader));
        Marshal.FreeHGlobal(ptr);
    }

I would check to make sure you are following these guidelines Marshaling Structures in the .NET Compact Framework

Another option is to copy the fields from your buffer to your structure manually byte by byte. You could write a function that returns a SFHeader and takes a byte[].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM