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[].
链接地址: http://www.djcxy.com/p/53684.html上一篇: 如何在紧凑框架中记录操作?