简体   繁体   English

在 Compact Framework 中将字节数组转换为结构

[英]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.其中SFHeader是我的结构。

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.当我从智能设备项目运行此代码时抛出NotSupportedException Are there others methods to do this work in the Compact Framework?在 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. Marshal.PtrToStructure 有效,我在紧凑型框架中多次使用它。 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)因此,问题一定是您的结构定义(结构的 CF 中可能不支持某些内容)

The following code runs just fine on my device using Windows CE 5.0 and .NET CF 3.5以下代码在我使用 Windows CE 5.0 和 .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我会检查以确保您遵循这些准则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[].您可以编写一个返回 SFHeader 并采用 byte[] 的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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