C#下如何使用struct进行文件二进制读写

C#读取文件时,需要用到struct,但是对于数组类型,如何定义长度?如何保证struct与字节对齐。本文已经验证读写OK,但其代表的功能不正确。
public class HzkBin

{
    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    struct FL_Header
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
        public byte[] magic ; //'U'('S', 'M'), 'F', 'L', X---Unicode(Simple or MBCS), X: Version
        public UInt32 dwFileSize; /* File total size */
        public byte nSection; /* total sections */
        public byte YSize; /* height of font */
        public UInt16 wCpFlag; /* codepageflag 每个 bit 位表示一个字符集。即最多可表示 16 个字符集。*/
        public UInt16 nTotalChars; /* 总的有效字符数 */
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
        public char[] reserved;
    }

    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    struct FL_SECTION_INF
    {
        public UInt16 First; /* first character */
        public UInt16 Last; /* last character */
        public UInt32 OffAddr; /* 指向的是当前 SECTION 包含的 UFL_CHAR_INFO 第一个字符信息的起始地址 */
    }

    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    struct UFL_CHAR_INDEX
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
        byte[] data;
        public ushort Width
        {
            get
            {
                if (data!=null && data.Length==4)
                {
                    ushort m = (ushort)data[3];
                    m >>= 2;
                    return m ;
                }
                return 0;
            }
        }
        public UInt32 OffAddr
        {
            get
            {
                if (data != null && data.Length == 4)
                {
                    UInt32 m = BitConverter.ToUInt32(data, 0);
                    m <<= 6;
                    return m;
                }
                return 0;
            }
        }
        //UInt32 OffAddr : 26; // 当前字符点阵数据的起始地址
        //UInt32 Width : 6; // 字符点阵的像素的宽度( 目前最大支持点阵 < 64)
    }
    public byte[] ReadHzFzDataByEncoding(UInt16 hzEncoding)
    {
        System.IO.FileStream fs = new System.IO.FileStream("e:\\simfang_U16.bin", System.IO.FileMode.Open);

        FL_Header fL_Header=new FL_Header();
        //此处使用非安全代码来获取到StructDemo的值
        int size = Marshal.SizeOf(fL_Header);
        byte[] b = new byte[size];
        fs.Read(b, 0, size);
        fL_Header = (FL_Header)ByteToStruct(b, typeof(FL_Header));
        //读段信息
        FL_SECTION_INF[] fL_SECTION_INFs = new FL_SECTION_INF[fL_Header.nSection];
        FL_SECTION_INF fL_SECTION_INF = new FL_SECTION_INF();
        size = Marshal.SizeOf(fL_SECTION_INF);
        for (int i = 0; i < fL_Header.nSection; i++)
        {
            b = new byte[size];
            fs.Read(b, 0, size);
            fL_SECTION_INFs[i] = (FL_SECTION_INF)ByteToStruct(b, typeof(FL_SECTION_INF));
        }
        //差一个找区段过程

        //读检索表
        UFL_CHAR_INDEX uFL_CHAR_INDEX = new UFL_CHAR_INDEX();
        size = Marshal.SizeOf(uFL_CHAR_INDEX);
        long hzfzDataAddr = (hzEncoding - fL_SECTION_INFs[0].First) * size + fL_SECTION_INFs[0].OffAddr;

        fs.Seek(hzfzDataAddr, SeekOrigin.Begin);
        b = new byte[size];
        fs.Read(b, 0, size);
        uFL_CHAR_INDEX = (UFL_CHAR_INDEX)ByteToStruct(b, typeof(UFL_CHAR_INDEX));

        b = new byte[fL_Header.YSize * fL_Header.YSize / 8];
        fs.Seek(uFL_CHAR_INDEX.OffAddr, SeekOrigin.Begin);
        fs.Read(b, 0, uFL_CHAR_INDEX.Width);

        fs.Close();

        return b;
    }

    //将Byte转换为结构体类型
    public static byte[] StructToBytes(object structObj, int size)
    {
        int num = 2;
        byte[] bytes = new byte[size];
        IntPtr structPtr = Marshal.AllocHGlobal(size);
        //将结构体拷到分配好的内存空间
        Marshal.StructureToPtr(structObj, structPtr, false);
        //从内存空间拷贝到byte 数组
        Marshal.Copy(structPtr, bytes, 0, size);
        //释放内存空间
        Marshal.FreeHGlobal(structPtr);
        return bytes;
    }

    //将Byte转换为结构体类型
    public static object ByteToStruct(byte[] bytes, Type type)
    {
        int size = Marshal.SizeOf(type);
        if (size > bytes.Length)
        {
            return null;
        }
        //分配结构体内存空间
        IntPtr structPtr = Marshal.AllocHGlobal(size);
        //将byte数组拷贝到分配好的内存空间
        Marshal.Copy(bytes, 0, structPtr, size);
        //将内存空间转换为目标结构体
        object obj = Marshal.PtrToStructure(structPtr, type);
        //释放内存空间
        Marshal.FreeHGlobal(structPtr);
        return obj;
    }
}

}

评论

暂无评论