当前位置:网站首页>C byte array and class mutual conversion
C byte array and class mutual conversion
2022-07-24 01:29:00 【Wu Zimu】
When doing serial communication , Encountered a very interesting way of writing
The serial port information here is not a string , But a class represented by a byte array
Note that this is not json character string , It's an array of bytes
The idea is to open up a piece of memory in memory , Insert byte array into memory , Then encapsulate this memory as an object of the corresponding class
The code is as follows
Need to quote
using System.Runtime.InteropServices;
/// <summary>
/// Byte to byte RtuAck Structure
/// </summary>
/// <param name="arr"></param>
public RtuAck Bytes2Ack(byte[] arr)
{
RtuAck ack = new RtuAck();
int size = Marshal.SizeOf(ack);
IntPtr ptr = Marshal.AllocHGlobal(size); // Declare an unmanaged memory , To hold arr
Marshal.Copy(arr, 0, ptr, size);// take arr Stored in the declared memory
ack = (RtuAck)Marshal.PtrToStructure(ptr, ack.GetType());// Turn this memory into ack type
Marshal.FreeHGlobal(ptr);// Release the unmanaged memory just declared
return ack;
}
conversely , The code for transferring from class object to byte array is as follows
public byte[] Ack2Bytes(RtuAck ack)
{
int size = Marshal.SizeOf(ack);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(ack, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
边栏推荐
- Measurement and acquisition of permanent magnet motor parameters (inductance, resistance, pole number, flux linkage constant)
- How to solve cnpm stuck during execution?
- Hcip day 9 notes
- Polymer synthesis technology
- HCIP第六天_特殊区域综合实验
- [freeswitch development practice] column introduction
- Retinal network based on enhanced spatial attention (ESA UNET)
- How safe is Volvo XC90? 5 seats and 7 seats are available
- RIP(第二天笔记)
- Hcip seventh day notes
猜你喜欢

HCIP第十一天笔记

Matlab绘制双坐标图(全网最简单)
刚开始使用,请教些问题和教程或分享帖子

Arm architecture and programming 1 -- LED flashing (based on Baiwen arm architecture and programming tutorial video)

HCIP中的MGRE GRE OSPF过程

Problèmes de localisation et de planification des itinéraires (Lingo, mise en œuvre de MATLAB)

HCIA的复习

Arm architecture and programming 6 -- Relocation (based on Baiwen arm architecture and programming tutorial video)

OSI、TCP/IP(A1)

Navicat for MySQL installation tutorial
随机推荐
Hcip third day notes
Research on retinal vascular segmentation based on GAN using few samples
基于强化空间注意力的视网膜网络(ESA-Unet)
罗克韦尔AB PLC RSLogix5000中的位指令使用方法介绍
How safe is Volvo XC90? 5 seats and 7 seats are available
沃尔沃xc90的安全性如何?提供5座和7座可选
Hcip day 8 notes
HCIP第七天笔记
Disadvantages of win11
OSPF (fifth day notes)
Data warehouse construction - ods floor
HCIP第二天笔记
A little understanding of encoder
HCIP第四天笔记
OSPF(第六天笔记)
数字签名技术简介
HCIP第十一天笔记
HCIP实验
Code reading methods and best practices
SCM learning notes 7 -- systick timer (based on Baiwen STM32F103 series tutorials)