当前位置:网站首页>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; }
}
边栏推荐
- openmv4 学习笔记1----一键下载、图像处理背景知识、LAB亮度-对比度
- 数学知识——高斯消元(初等行变换解方程组)代码实现
- Detailed idea and code implementation of infix expression to suffix expression
- 裕太微冲刺科创板:拟募资13亿 华为与小米基金是股东
- test about BinaryTree
- Characteristic colleges and universities, jointly build Netease Industrial College
- 关于静态类型、动态类型、id、instancetype
- The nearest library of Qinglong panel
- 打家劫舍III[后序遍历与回溯+动态规划]
- 五金机电行业供应商智慧管理平台解决方案:优化供应链管理,带动企业业绩增长
猜你喜欢
能源行业的数字化“新”运维
基于蝴蝶种类识别
A wearable arm device for night and sleeveless blood pressure measurement [translation]
ROS自定义消息发布订阅示例
保证接口数据安全的10种方案
AUTOCAD——中心线绘制、CAD默认线宽是多少?可以修改吗?
业务与应用同步发展:应用现代化的策略建议
MRO工业品企业采购系统:如何精细化采购协同管理?想要升级的工业品企业必看!
Interface test tool - postman
If you have any problems, you can contact me. A rookie ~
随机推荐
test about BinaryTree
R语言ggplot2可视化:使用ggpubr包的ggviolin函数可视化小提琴图
Fast power template for inverse element, the role of inverse element and example [the 20th summer competition of Shanghai University Programming League] permutation counting
Helm deploy etcd cluster
JDBC详解
打家劫舍III[后序遍历与回溯+动态规划]
保证接口数据安全的10种方案
How are you in the first half of the year occupied by the epidemic| Mid 2022 summary
R language uses the order function to sort the dataframe data, and descending sorting based on a single field (variable)
An error occurs when installing MySQL: could not create or access the registry key needed for the
【论文笔记】TransUNet: Transformers Make StrongEncoders for Medical Image Segmentation
test about BinaryTree
Modulenotfounderror: no module named 'PIL' solution
Pychrm Community Edition calls matplotlib pyplot. Solution of imshow() function image not popping up
openmv4 学习笔记1----一键下载、图像处理背景知识、LAB亮度-对比度
Human bone point detection: top-down (part of the theory)
Unlock 2 live broadcast themes in advance! Today, I will teach you how to complete software package integration Issues 29-30
业务与应用同步发展:应用现代化的策略建议
Qlabel marquee text display
Excel 中VBA脚本的简单应用