当前位置:网站首页>C # - realize serialization with Marshall class
C # - realize serialization with Marshall class
2022-07-06 19:16:00 【luckyone906】
Mainly used Marshal Two methods in class :
The first is StructureToPtr, Marshaling data from managed objects to unmanaged memory blocks .
The second is PtrToStructure, Marshals data from an unmanaged memory block to a newly allocated managed object of the specified type .
As long as there are these two methods of mutual transformation , We can realize serialization .
First, let's look at serialization
serialize :
There is a prerequisite , That is, we must know the size of the serialized object .
First step : Let's find out the size of the object first , Then allocate the corresponding memory size to it in unmanaged memory .
The second step : Then we will send this object to the memory just allocated , Then we will get a pointer to the first address of the allocated memory block .
The third step : Finally, we can use this first address pointer , Start at the position indicated by the pointer , Copy data to the specified byte[] Array , The length of the copy is the amount of memory we allocate for this object , obtain byte[] After the data , I don't need to say more about the following things , You can save to database Or in the file .
Deserialization :
When serializing, we first marshal an object into an unmanaged memory block , Then read the data in the memory block to byte[] Array ,
Now we deserialize
First step : Let's find out the size of the object first , Then allocate the corresponding memory size to it in unmanaged memory .
The second step : And put this byte[] Copy the data to an unmanaged memory block .
The third step : Finally, marshal the data of the specified size from the memory block to the object .
There is one thing to note , That is because we cannot find the actual size of an object of reference type , So we can only use unmanaged objects , such as struct Structure .
therefore , When we just use it to store data , Objects that do not involve any operations , We can treat it as a structure , In this way, we can save space when serializing .
Because if you use the usual serialization method to serialize a class object , It requires more space than you need to serialize a with the same structure struct object .
Here is the code :
public static class MyConverter{/// <summary>/// From structure to byte Array/// </summary>public static byte[] StructureToByte<T>(T structure){int size = Marshal.SizeOf(typeof(T));byte[] buffer = new byte[size];IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);try{Marshal.StructureToPtr(structure, bufferIntPtr, true);Marshal.Copy(bufferIntPtr, buffer, 0, size);}finally{Marshal.FreeHGlobal(bufferIntPtr);}return buffer;}/// <summary>/// from byte The array is converted to a structure/// </summary>public static T ByteToStructure<T>(byte[] dataBuffer){object structure = null;int size = Marshal.SizeOf(typeof(T));IntPtr allocIntPtr = Marshal.AllocHGlobal(size);try{Marshal.Copy(dataBuffer, 0, allocIntPtr, size);structure = Marshal.PtrToStructure(allocIntPtr, typeof(T));}finally{Marshal.FreeHGlobal(allocIntPtr);}return (T)structure;}}// Test code ///class Program{static void Main(string[] args){Student student1 = new Student { Name = " Huchangjun ", ID = 2 };Console.WriteLine(" Before serialization => full name :{0} ID:{1}", student1.ID, student1.Name);byte[] bytes = MyConverter.StructureToByte<Student>(student1);Student sudent2 = MyConverter.ByteToStructure<Student>(bytes);Console.WriteLine(" After serialization => full name :{0} ID:{1}", sudent2.ID, sudent2.Name);Console.Read();}}public struct Student{public int ID { get; set; }public string Name { get; set; }}
边栏推荐
- 关于静态类型、动态类型、id、instancetype
- The list of people who passed the fifth phase of personal ability certification assessment was published
- 裕太微冲刺科创板:拟募资13亿 华为与小米基金是股东
- Cereals Mall - Distributed Advanced p129~p339 (end)
- Take a look at how cabloyjs workflow engine implements activiti boundary events
- 黑馬--Redis篇
- R语言ggplot2可视化:使用ggpubr包的ggstripchart函数可视化分组点状条带图(dot strip plot)、设置add参数为不同水平点状条带图添加箱图
- 黑马--Redis篇
- Graffiti intelligence is listed on the dual main board in Hong Kong: market value of 11.2 billion Hong Kong, with an annual revenue of 300 million US dollars
- AcWing 3537. Tree lookup complete binary tree
猜你喜欢

五金机电行业智能供应链管理系统解决方案:数智化供应链为传统产业“造新血”

Synchronous development of business and application: strategic suggestions for application modernization
Benefit a lot, Android interview questions
![Airiot IOT platform enables the container industry to build [welding station information monitoring system]](/img/52/88e3c7b7a60867282921d9bb5c96da.jpg)
Airiot IOT platform enables the container industry to build [welding station information monitoring system]

Computer network: sorting out common network interview questions (I)
Interview assault 63: how to remove duplication in MySQL?

AUTOCAD——中心线绘制、CAD默认线宽是多少?可以修改吗?

基于蝴蝶种类识别

How to improve website weight

安装Mysql报错:Could not create or access the registry key needed for the...
随机推荐
青龙面板最近的库
map的使用(列表的数据赋值到表单,json逗号隔开显示赋值)
R language ggplot2 visualization: use ggviolin function of ggpubr package to visualize violin diagram
中缀表达式转后缀表达式详细思路及代码实现
pychrm社区版调用matplotlib.pyplot.imshow()函数图像不弹出的解决方法
php+redis实现超时取消订单功能
倒计时2天|腾讯云消息队列数据接入平台(Data Import Platform)直播预告
Multithreading Basics: basic concepts of threads and creation of threads
Interface test tool - postman
Mathematical knowledge -- code implementation of Gaussian elimination (elementary line transformation to solve equations)
Word如何显示修改痕迹
Oracle advanced (IV) table connection explanation
Actf 2022 came to a successful conclusion, and 0ops team won the second consecutive championship!!
快速幂模板求逆元,逆元的作用以及例题【第20届上海大学程序设计联赛夏季赛】排列计数
今日直播 | “人玑协同 未来已来”2022弘玑生态伙伴大会蓄势待发
2022.2.12
受益匪浅,安卓面试问题
Test technology stack arrangement -- self cultivation of test development engineers
If you have any problems, you can contact me. A rookie ~
About NPM install error 1