C# 结构体与Bytes互转

 C#开发上位机时,很多情况需要将字节流与结构体进行转换,下面代码是结构体与bytes互转示例代码。

        public static byte[] StructToBytes<T>(T obj)
        {
            int size = Marshal.SizeOf(typeof(T));
            IntPtr bufferPtr = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(obj, bufferPtr, false);
                byte[] bytes = new byte[size];
                Marshal.Copy(bufferPtr, bytes, 0, size);
                return bytes;
            }
            catch (Exception ex)
            {
                throw new Exception("Error in StructToBytes ! " + ex.Message);
            }
            finally
            {
                Marshal.FreeHGlobal(bufferPtr);
            }
        }

        public static object BytesToStuct(byte[] bytes, Type type)
        {
            //得到结构体的大小
            int size = Marshal.SizeOf(type);
            //byte数组长度小于结构体的大小
            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;
        }

        public struct desc_info_t
        {
            public uint magic_num;    //allways be 0x20200710
            public uint size;         //file size
            public uint file_type;    //file type
            public uint method;       //(reserve)differential upgrade
            public uint chk_sum;      //check sum, for ota
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 28)]
            public byte[] device;   //device name, such as "UE-E210"
        }
        public struct header_t
        {
            public uint prefix;       //prefix: 0x20200655(LSB must 0x55)
            public uint ver;          //version of upgrade protocal
            public uint baudrate;     //auto switch baudrate
            public uint en_485;       //RS485 enable 0: disable 1: enable
            public uint broadcast;    //骞挎挱
            public desc_info_t info;         //file descriptor
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 60)]
            public byte[] path;
        }

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言中没有原生支持JSON的数据类型和操作,但是可以通过第三方库实现C结构和JSON的。以下是使用cJSON库实现C结构和JSON的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include "cJSON.h" typedef struct { int id; char name[20]; double score; } Student; // 将C结构换为JSON字符串 char* struct_to_json(Student* stu) { cJSON* root = cJSON_CreateObject(); cJSON_AddNumberToObject(root, "id", stu->id); cJSON_AddStringToObject(root, "name", stu->name); cJSON_AddNumberToObject(root, "score", stu->score); char* json_str = cJSON_Print(root); cJSON_Delete(root); return json_str; } // 将JSON字符串换为C结构 Student* json_to_struct(const char* json_str) { cJSON* root = cJSON_Parse(json_str); Student* stu = (Student*)malloc(sizeof(Student)); stu->id = cJSON_GetObjectItem(root, "id")->valueint; strcpy(stu->name, cJSON_GetObjectItem(root, "name")->valuestring); stu->score = cJSON_GetObjectItem(root, "score")->valuedouble; cJSON_Delete(root); return stu; } int main() { // 创建一个C结构 Student stu = { 1, "Tom", 90.5 }; // 将C结构换为JSON字符串 char* json_str = struct_to_json(&stu); printf("JSON string: %s\n", json_str); // 将JSON字符串换为C结构 Student* new_stu = json_to_struct(json_str); printf("ID: %d, Name: %s, Score: %.1f\n", new_stu->id, new_stu->name, new_stu->score); // 释放内存 free(json_str); free(new_stu); return 0; } ``` 运行结果: ``` JSON string: {"id":1,"name":"Tom","score":90.5} ID: 1, Name: Tom, Score: 90.5 ``` 注意,在使用cJSON库时,需要在代码中引用cJSON.h头文件,并且需要在编译时链接cJSON库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值