【转】C# struct byte 互转

文章来源(侵联删):
https://blog.csdn.net/shenaisi/article/details/104727187

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace struct_test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            TestStruct temp_struct = new TestStruct();
            temp_struct.c = 1234;
            temp_struct.str = "abdcefg";
            temp_struct.test = new int[6];
            temp_struct.test[0] = 1;
            temp_struct.test[1] = 2;
            temp_struct.test[2] = 3;
            temp_struct.test[3] = 4;
            temp_struct.test[4] = 5;
            temp_struct.test[5] = 6;
            byte[] test_bytes = StructToBytes(temp_struct);
            foreach (var c in test_bytes) {
                System.Console.Write("{0} ", c);
            }
            TestStruct temp_struct2 = (TestStruct)BytesToStuct(test_bytes, typeof(TestStruct));
            System.Console.ReadLine();
        }

        static byte[] StructToBytes(object structObj)
        {
            int size = Marshal.SizeOf(structObj);
            byte[] bytes = new byte[size];
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(structObj, structPtr, false);
            Marshal.Copy(structPtr, bytes, 0, size);
            Marshal.FreeHGlobal(structPtr);
            return bytes;
        }

        static object BytesToStuct(byte[] bytes, Type type)
        {
            int size = Marshal.SizeOf(type);
            if (size > bytes.Length)
            {
                return null;
            }
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            Marshal.Copy(bytes, 0, structPtr, size);
            object obj = Marshal.PtrToStructure(structPtr, type);
            Marshal.FreeHGlobal(structPtr);
            return obj;
        }
    }

    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    struct TestStruct
    {
        public int c;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string str;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
        public int[] test;
    }

}

posted @ 2024-08-12 10:58  坚持梦想的蜗牛  阅读(7)  评论(0编辑  收藏  举报