当前位置:网站首页>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; }}
边栏推荐
- LeetCode-1279. 红绿灯路口
- Use of deg2rad and rad2deg functions in MATLAB
- 抽象类与抽象方法
- Tensorflow and torch code verify whether CUDA is successfully installed
- 全套教学资料,阿里快手拼多多等7家大厂Android面试真题
- JDBC详解
- [depth first search] Ji suanke: find numbers
- Three years of Android development, Android interview experience and real questions sorting of eight major manufacturers during the 2022 epidemic
- wx小程序学习笔记day01
- Interview assault 63: how to remove duplication in MySQL?
猜你喜欢

Don't miss this underestimated movie because of controversy!

MRO工业品企业采购系统:如何精细化采购协同管理?想要升级的工业品企业必看!

Help improve the professional quality of safety talents | the first stage of personal ability certification and assessment has been successfully completed!

LeetCode-1279. 红绿灯路口

渲大师携手向日葵,远控赋能云渲染及GPU算力服务

wx小程序学习笔记day01
![Deep circulation network long-term blood pressure prediction [translation]](/img/9c/c1ed28242a4536c1e8fde3414f82a8.png)
Deep circulation network long-term blood pressure prediction [translation]

史上超级详细,想找工作的你还不看这份资料就晚了
![[translation] a GPU approach to particle physics](/img/07/57036c925155cab36678c696e89440.jpg)
[translation] a GPU approach to particle physics

How to improve website weight
随机推荐
史上超级详细,想找工作的你还不看这份资料就晚了
A full set of teaching materials, real questions of Android interview of 7 major manufacturers including Alibaba Kwai pinduoduo
渲大师携手向日葵,远控赋能云渲染及GPU算力服务
wx小程序学习笔记day01
An error occurs when installing MySQL: could not create or access the registry key needed for the
Pytorch common loss function
LeetCode-1279. 红绿灯路口
map的使用(列表的数据赋值到表单,json逗号隔开显示赋值)
AutoCAD - what is the default lineweight for centerline drawing and CAD? Can I modify it?
AcWing 3537. Tree lookup complete binary tree
short i =1; i=i+1与short i=1; i+=1的区别
Binary search tree
Looting iii[post sequence traversal and backtracking + dynamic planning]
Analysis of frequent chain breaks in applications using Druid connection pools
AUTOCAD——中心线绘制、CAD默认线宽是多少?可以修改吗?
R语言使用dt函数生成t分布密度函数数据、使用plot函数可视化t分布密度函数数据(t Distribution)
Simple understanding of MySQL database
Human bone point detection: top-down (part of the theory)
Help improve the professional quality of safety talents | the first stage of personal ability certification and assessment has been successfully completed!
The nearest library of Qinglong panel