使用Wesky.Net.OpenTools包来快速实现嵌套型结构体数据转换功能

news/2024/10/3 8:19:41
今天遇到有人提到结构体和byte数组互转的问题,我就顺便拿来水一篇。这是一个冷门的问题,估计使用的人不多。既然有需求,应该就有使用场景,那就顺便整一波。
为了达到效果,结构体、复杂结构体嵌套等都能实现转换,我就顺便做了个包更新来提供使用和下面的说明。
首先引入nuget包 Wesky.Net.OpenTools 的最新版
0
 
新建几个结构体做实验。结构体结构如下所示,做四个层级的嵌套,包括数组、基础类型、结构体数组和嵌套等。
0
 
使用方式:
对结构体属性进行赋值等操作,模拟一个我们要做的对象数据。
0
实例化一个转换器
0
转换器选择方式有两种,一种针对基础类型的操作,用Marshal自带的方法进行实现。另一种为复杂类型的转换实现。此处主要演示第二种(上面结构体会自动选择第二种转换器)
转换器选择内部实现源码如下:
 1 /// <summary>
 2 /// 提供结构体转换器的工厂类。
 3 /// Provides a factory class for structure converters.
 4 /// </summary>
 5 public class StructConvertFactory
 6 {
 7     /// <summary>
 8     /// 根据结构体类型的复杂性选择合适的转换器。
 9     /// Selects an appropriate converter based on the complexity of the structure type.
10     /// </summary>
11     /// <typeparam name="T">要为其创建转换器的结构体类型。</typeparam>
12     /// <returns>返回符合结构体类型特性的转换器实例。</returns>
13     /// <remarks>
14     /// 如果结构体包含复杂字段,则返回一个基于反射的转换器,否则返回一个基于内存操作的转换器。
15     /// If the structure contains complex fields, a reflection-based converter is returned; otherwise, a memory operation-based converter is provided.
16     /// </remarks>
17     public static IStructConvert CreateConvertor<T>() where T : struct
18     {
19         // 判断结构体类型T是否包含复杂字段
20         if (HasComplexFields(typeof(T)))
21         {
22             // 返回反射方式实现的结构体转换器
23             return new StructConvert();
24         }
25         else
26         {
27             // 返回Marshal自带的操作方式实现的结构体转换器
28             return new MarshalConvert();
29         }
30     }
31 
32     /// <summary>
33     /// 验证指定类型的字段是否包含复杂类型。
34     /// Verifies whether the fields of the specified type contain complex types.
35     /// </summary>
36     /// <param name="type">要检查的类型。</param>
37     /// <returns>如果包含复杂类型字段,则返回true;否则返回false。</returns>
38     /// <remarks>
39     /// 复杂类型包括数组、类以及非基本的值类型(如结构体),但不包括decimal。
40     /// Complex types include arrays, classes, and non-primitive value types such as structures, but exclude decimal.
41     /// </remarks>
42     private static bool HasComplexFields(Type type)
43     {
44         foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
45         {
46             if (field.FieldType.IsArray || field.FieldType.IsClass ||
47                 (field.FieldType.IsValueType && !field.FieldType.IsPrimitive &&
48                  field.FieldType != typeof(decimal)))
49             {
50                 return true;
51             }
52         }
53         return false;
54     }
55 }

 

转换器都继承自IStructConvert接口,IStructConvert接口定义如下
 1 /// <summary>
 2 /// IStructConvert 接口,提供结构体与字节数组之间的序列化和反序列化功能。
 3 /// IStructConvert interface, providing serialization and deserialization functionality between structures and byte arrays.
 4 /// </summary>
 5 public interface IStructConvert
 6 {
 7     /// <summary>
 8     /// 将字节数组反序列化为结构体。
 9     /// Deserializes a byte array into a structure.
10     /// </summary>
11     /// <typeparam name="T">结构体的类型。</typeparam>
12     /// <param name="data">包含结构体数据的字节数组。</param>
13     /// <returns>反序列化后的结构体实例。</returns>
14     byte[] StructToBytes<T>(T structure) where T : struct;
15 
16     /// <summary>
17     /// 将结构体实例转换为字节数组。
18     /// Converts a structure instance into a byte array.
19     /// </summary>
20     /// <typeparam name="T">要转换的结构体类型,必须是值类型。</typeparam>
21     /// <param name="structure">要转换的结构体实例。</param>
22     /// <returns>表示结构体数据的字节数组。</returns>
23     T BytesToStruct<T>(byte[] data) where T : struct;
24 }

 

所以下面我们可以直接调用转换器的这两个方法来实现数据的转换:
0
设置断点,执行程序。监视到byte数组的data数据有77个元素
0
继续监控数组数据转换回来的数据,可以对比到对象的数据和上面定义的内容是一致的,说明数据转换成功。
0
其他核心代码——MarshalConvert类转换器代码:
 1   /// <summary>
 2   /// 实现IStructConvert接口,提供结构体与字节数组间的基本转换功能。
 3   /// Implements the IStructConvert interface to provide conversion between structures and byte arrays.
 4   /// </summary>
 5   public class MarshalConvert : IStructConvert
 6   {
 7       /// <summary>
 8       /// 将字节数组转换为指定类型的结构体实例。
 9       /// Converts a byte array into an instance of the specified type of structure.
10       /// </summary>
11       /// <typeparam name="T">要转换的结构体类型,必须是值类型。</typeparam>
12       /// <param name="data">包含结构体数据的字节数组。</param>
13       /// <returns>转换后的结构体实例。</returns>
14       public T BytesToStruct<T>(byte[] data) where T : struct
15       {
16           T structure;
17           // 计算结构体类型T的内存大小
18           // Calculate the memory size of the structure type T
19           int size = Marshal.SizeOf(typeof(T));
20           // 分配相应大小的内存缓冲区
21           // Allocate a memory buffer of the appropriate size
22           IntPtr buffer = Marshal.AllocHGlobal(size);
23           try
24           {
25               // 将字节数组复制到分配的内存中
26               // Copy the byte array to the allocated memory
27               Marshal.Copy(data, 0, buffer, size);
28               // 将内存缓冲区转换为指定的结构体
29               // Convert the memory buffer to the specified structure
30               structure = Marshal.PtrToStructure<T>(buffer);
31           }
32           finally
33           {
34               // 释放内存缓冲区
35               // Free the memory buffer
36               Marshal.FreeHGlobal(buffer);
37           }
38           return structure;
39       }
40 
41       /// <summary>
42       /// 将结构体实例转换为字节数组。
43       /// Converts a structure instance into a byte array.
44       /// </summary>
45       /// <typeparam name="T">要转换的结构体类型,必须是值类型。</typeparam>
46       /// <param name="structure">要转换的结构体实例。</param>
47       /// <returns>表示结构体数据的字节数组。</returns>
48       public byte[] StructToBytes<T>(T structure) where T : struct
49       {
50           // 计算结构体实例的内存大小
51           // Calculate the memory size of the structure instance
52           int size = Marshal.SizeOf(structure);
53           byte[] array = new byte[size];
54           // 分配相应大小的内存缓冲区
55           // Allocate a memory buffer of the appropriate size
56           IntPtr buffer = Marshal.AllocHGlobal(size);
57           try
58           {
59               // 将结构体实例复制到内存缓冲区
60               // Copy the structure instance to the memory buffer
61               Marshal.StructureToPtr(structure, buffer, false);
62               // 将内存缓冲区的数据复制到字节数组
63               // Copy the data from the memory buffer to the byte array
64               Marshal.Copy(buffer, array, 0, size);
65           }
66           finally
67           {
68               // 释放内存缓冲区
69               // Free the memory buffer
70               Marshal.FreeHGlobal(buffer);
71           }
72           return array;
73       }
74   }

 

如果以上内容对你有帮助,欢迎点赞、转发、在看和关注我的个人公众号:【Dotnet Dancer
如果需要以上演示代码,可以在公众号【Dotnet Dancer】后台回复“结构体转换”进行获取。
OpenTools系列文章快捷链接【新版本完全兼容旧版本,不需要更新任何代码均可使用】:
1.0.13版本
快速实现.NET(.net framework/.net core+)动态访问webservice服务
https://mp.weixin.qq.com/s/KoLpaBaYX7_ETP0dfgQfyw
1.0.11版本
如何一行C#代码实现解析类型的Summary注释(可用于数据字典快速生成)
https://mp.weixin.qq.com/s/CWqubRRMoYVQIQJSyjIUXg
1.0.10版本:
C#/.NET一行代码把实体类类型转换为Json数据字符串
https://mp.weixin.qq.com/s/nVcURD0lf5-AQOVzwHqcxw
1.0.8版本:
上位机和工控必备!用.NET快速搞定Modbus通信的方法
https://mp.weixin.qq.com/s/Yq6kuXzFglHfNUqrHcQO9w
1.0.7版本:
大揭秘!.Net如何在5分钟内快速实现物联网扫码器通用扫码功能?
https://mp.weixin.qq.com/s/-5VuLAS6HlElgDQXRY9-BQ
1.0.6版本:
.NET实现获取NTP服务器时间并同步(附带Windows系统启用NTP服务功能)
https://mp.weixin.qq.com/s/vMW0vYC-D9z0Dp6HFSBqyg
1.0.5版本:
C#使用P/Invoke来实现注册表的增删改查功能
https://mp.weixin.qq.com/s/LpsjBhDDzkwyLU_tIpF-lg
1.0.3版本:
C#实现图片转Base64字符串,以及base64字符串在Markdown文件内复原的演示
https://mp.weixin.qq.com/s/n9VtTCIiVUbHJk7OfoCcvA
1.0.2版本:
​C#实现Ping远程主机功能(支持IP和域名)
https://mp.weixin.qq.com/s/d-2HcIM1KaLo-FrrTLkwEw
1.0.1版本:
开始开源项目OpenTools的创作(第一个功能:AES加密解密)
https://mp.weixin.qq.com/s/78TA-mst459AuvAHwQViqQ
 
【备注】包版本完全开源,并且没有任何第三方依赖。使用.net framework 4.6+、任意其他跨平台.net版本环境,均可直接引用。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hjln.cn/news/44658.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

gophish钓鱼

目录环境介绍安装1、设置发件人的邮箱2、编辑钓鱼邮件模板3、制作钓鱼页面4、设置目标用户5、创建钓鱼事件6、查看结果 参考1 参考2 参考3 Gophish官网并下载适用于Linux的版本 环境介绍 Ubuntu22图形化/16G/4U/120G 172.16.186.137/24安装 rambo@test1:~$ mkdir gophish &…

NumPy 舍入小数、对数、求和和乘积运算详解

NumPy 提供五种舍入小数的方法:`trunc()`, `fix()`, `around()`, `floor()`, `ceil()`。此外,它还支持对数运算,如 `log2()`, `log10()`, `log()`,以及自定义底数的对数。NumPy 的 `sum()` 和 `prod()` 函数用于数组求和与乘积,可指定轴进行计算,`cumsum()` 和 `cumprod(…

微博-指定话题当日数据爬取

该文章详细描述了如何通过分析和抓包技术,绕过微博网页端和手机端的数据访问限制,使用Python脚本爬取与特定关键词(如"巴以冲突")相关的微博数据。文章首先探讨了网页端微博数据爬取的局限性,如需要登录账号和数据量限制,然后转向手机端,发现其对爬虫更为友好…

ZYNQ LINUX如何开机自动执行指定脚本

本意是想要开机后自动加载某内核驱动,并且执行指定应用程序。在 /etc/init.d/rc 末尾增加指定脚本执行即可。脚本内容 insmod /usr/u-dma-buf.ko

20240612-vscode中oh-my-posh下powershell指定profile.ps1默认文件

vscode下遇到了命令提示符带有一串未知字符的问题,尝试get-poshthemes发现没有出现这些字符,于是判断可能是powershell的profile.ps1中主题相关的文件配置出了问题,打算换个主题。修改了profile.ps1文件之后,windows terminal下powershell可以正常生效,但是vscode却不行,…

FastAPI-8:Web层

8 Web层 本章将进一步介绍FastAPI应用程序的顶层(也可称为接口层或路由器层)及其与服务层和数据层的集成。 一般来说,我们如何处理信息?与大多数网站一样,我们的网站将提供以下方法:检索 创建 修改 替换 删除8.1 插曲: 自顶向下、自底向上、中间向外?(Top-Down, Bottom…

模拟epoll的饥饿场景

说明 一直听说epoll的饥饿场景,但是从未在实际环境中面对过,那么能不能模拟出来呢?实际的情况是怎样呢? 模拟步骤基于epoll写一个简单的tcp echo server,将每次read返回的字节数打印出来 模拟一个客户端大量写入 测试其他客户端能否正常返回Server代码 #include <stdio…

浪潮服务器做 RAID 的方式

一次充实的装系统体验,非常感谢耐心的浪潮售后技术,没有他就没有这篇博文 由于按Ctrl + H 和 Ctrl + R 进不去 RAID,网上也没有合适的教程 于是使用工程师最有效的手段打电话 摇 人 首先把产品的序列号准备好浪潮服务器客服:400-860-0011关注微信公众号:浪潮信息专家服务 …