当前位置:网站首页>C structure use
C structure use
2022-07-28 12:41:00 【yi_ tianchou】
Upper computer (C#) It needs to transmit data with MCU through serial port , I also stepped on several pits before realizing this function , Time is in a hurry , Scribbled , There are unclear questions to ask .
The interface and data format have been defined on the single chip microcomputer ( structure )
Processing method on upper computer :
1、 Serial port received byte Array , Press the subscript to get
If the data structure is single, this method is not impossible , If there are many data structures , The structure is large Then we need to calculate the subscript carefully , Otherwise, it is easy to have problems , And it's not easy to maintain .
for example :
private void sp_DataReceived(object sender, EventArgs e)
{
SerialPort sp1 = (SerialPort)sender;
if (sp1.IsOpen) // Judge whether to open the serial port
{
try
{
if (this.InvokeRequired) // Add thread to prevent fake death
{
this.Invoke(new MethodInvoker(delegate
{
int int_len = sp1.BytesToRead;
byte[] b = new byte[sp1.BytesToRead];
sp1.Read(b, 0, b.Length); // byte
myBuffer.AddRange(b);
while (myBuffer.Count >= 15)// At least equal to the header length
{
if (myBuffer[0] == 0xf9 && Array.IndexOf(CMDS, myBuffer[1]) >= 0)
{
int strLen = (myBuffer[2] << 8) + myBuffer[3]+6;
if (strLen > myBuffer.Count)
{
break;
}
int cmpType = (myBuffer[5] << 8) + myBuffer[6];
switch (cmpType)
{
case 0x0B11:
sp.DiscardInBuffer();
sp.DiscardOutBuffer();
myBuffer.RemoveRange(0, myBuffer.Count);
break;
default:
break;
}
myBuffer.RemoveRange(0, myBuffer.Count);
}
else
{
myBuffer.RemoveRange(0, 1);
}
}
}));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}Method 2 Define the data structure on the single chip microcomputer to On the upper computer
1、 Define the same structure for the single product machine For receiving data ( SCM has defined #parama pack(1)) All in all SCM and On the upper computer pack(x) Should agree
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct TEST
{
byte a;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 28)]
byte[] b;/
byte c;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 28)]
char[] d;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 200)]
string e;// What is the length defined on the SCM
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)]
string login_data;//
}matters needing attention : 1、[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] Is the alignment of the structure ,pack=1 It means that the alignment of the structure is 1 byte . Otherwise, the default is 4 Bytes , Don't specify pack The way , You will find the same structure ,sizeof( structure ) Different sizes , So much so that byte When converting an array to a structure , The data does not correspond to ,
If not used or [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)] in UnmanagedType.ByValTStr Does not correspond to elements in the structure , Use in use sizeof I will report
Marshal.SizeOf newspaper “ Cannot Marshal as an unmanaged structure ; No meaningful size or offset can be calculated “ error .
2、 SCM string use char[200], Fixed length
c# Middle structure can be used string, But also set the length ( Fixed length use UnmanagedType.ByValTStr), How to fix the length
//
// Abstract :
// Used for arrays of inline fixed length characters that appear in structures .char Type is used for System.Runtime.InteropServices.UnmanagedType.ByValTStr
// Depending on System.Runtime.InteropServices.StructLayoutAttribute Attribute System.Runtime.InteropServices.CharSet
// Parameters apply to contained structures . Always use System.Runtime.InteropServices.MarshalAsAttribute.SizeConst
// Field to indicate the size of the array .
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 200)]
string e;// What is the length defined on the SCM
SCM string use unsigned char[28], Fixed length and UnmanagedType.ByValArray, Used to store Non string array
//
// Abstract :
// When System.Runtime.InteropServices.MarshalAsAttribute.Value Property is set to ByValArray when , You have to set
// System.Runtime.InteropServices.MarshalAsAttribute.SizeConst The field indicates the number of elements . Array of . When you need to distinguish between string types ,System.Runtime.InteropServices.MarshalAsAttribute.ArraySubType
// Field can select... Containing array elements System.Runtime.InteropServices.UnmanagedType. You can use this only System.Runtime.InteropServices.UnmanagedType
// The attributes of the fields in the structure in the form of elements in the array .
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 28)]
char[] d;
The structure and the array are mutually transformed :// Pseudo code
public TESTtest= new TEST();
Array to structure :
List<byte> myBuffer = new List<byte>();
private void sp_DataReceived(object sender, EventArgs e)
{
SerialPort sp1 = (SerialPort)sender;
if (sp1.IsOpen) // Judge whether to open the serial port
{
try
{
if (this.InvokeRequired) // Add thread to prevent fake death
{
this.Invoke(new MethodInvoker(delegate
{
// Thread.Sleep(20);
int int_len = sp1.BytesToRead;
byte[] b = new byte[sp1.BytesToRead];
sp1.Read(b, 0, b.Length); // byte
myBuffer.AddRange(b);
while (myBuffer.Count >= sizeof(TEST))// At least equal to the message length
{
try
{
test= (TEST)BytesToStruct(myBuffer.ToArray(), typeof(TEST));
}catch()
{
myBuffer.RemoveRange(0, 1);
}
}
myBuffer.RemoveRange(0, myBuffer.Count);
}
}
}));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}Structure to array :
byte[] s = StructToBytes(test);
Transformation method :
/// <summary>
/// The structure is transformed into byte[]
/// </summary>
/// <param name="structure"></param>
/// <returns></returns>
public static Byte[] StructToBytes(Object structure)
{
Int32 size = Marshal.SizeOf(structure);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, buffer, false);
Byte[] bytes = new Byte[size];
Marshal.Copy(buffer, bytes, 0, size);
return bytes;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
/// <summary>
/// byte[] Into a structure
/// </summary>
/// <param name="bytes"></param>
/// <param name="strcutType"></param>
/// <returns></returns>
public static Object BytesToStruct(Byte[] bytes, Type strcutType)
{
Int32 size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, 0, buffer, size);
return Marshal.PtrToStructure(buffer, strcutType);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
Statement : The conversion method is extracted from enthusiastic netizens , Investigation can be deleted
边栏推荐
- Use json.stringify() to format data
- Open source database innovation in the era of digital economy | the 2022 open atom global open source summit database sub forum was successfully held
- SuperMap arsurvey license module division
- 用C语言开发NES游戏(CC65)05、调色板
- [nuxt 3] (XII) project directory structure 3
- C# 结构使用
- 奥浦迈生物通过注册:半年营收1.47亿 国寿成达与达晨是股东
- 第九章 REST 服务安全
- How to build knowledge management system in enterprises and institutions
- 05 pyechars 基本图表(示例代码+效果图)
猜你喜欢
![[dark horse morning post] LETV 400 employees have no 996 and no internal papers; Witness history! 1 euro =1 US dollar; Stop immediately when these two interfaces appear on wechat; The crackdown on cou](/img/d7/4671b5a74317a8f87ffd36be2b34e1.jpg)
[dark horse morning post] LETV 400 employees have no 996 and no internal papers; Witness history! 1 euro =1 US dollar; Stop immediately when these two interfaces appear on wechat; The crackdown on cou

Use json.stringify() to format data

Hongjiu fruit passed the hearing: five month operating profit of 900million Ali and China agricultural reclamation are shareholders

Come to tdengine Developer Conference and have an insight into the future trend of data technology development

With the continuous waves of infringement, the U.S. patent and trademark office began to study the impact of NFT on copyright

Implementation method of mouse hover, click and double click in ue4/5

Aopmai biological has passed the registration: the half year revenue is 147million, and Guoshou Chengda and Dachen are shareholders

用C语言开发NES游戏(CC65)09、滚动

西门子对接Leuze BPS_304i 笔记

Kuzaobao: summary of Web3 encryption industry news on July 13
随机推荐
公司在什么情况下可以开除员工
遭受痛苦和创伤后的四种本真姿态 齐泽克
Hongjiu fruit passed the hearing: five month operating profit of 900million Ali and China agricultural reclamation are shareholders
GMT安装与使用
微创电生理通过注册:年营收1.9亿 微创批量生产上市企业
用C语言开发NES游戏(CC65)05、调色板
arduino pro mini ATMEGA328P 连线和点亮第一盏LED(同时记录烧录失败的问题stk500_recv)
Did kafaka lose the message
软件架构师必需要了解的 saas 架构设计?
Holes in [apue] files
C# 结构使用
Industry, University, research and application jointly build an open source talent ecosystem | the 2022 open atom global open source summit education sub forum was successfully held
How does musk lay off staff?
Library automatic reservation script
Aopmai biological has passed the registration: the half year revenue is 147million, and Guoshou Chengda and Dachen are shareholders
Sub database and sub table may not be suitable for your system. Let's talk about how to choose sub database and sub table and newsql
sqli-labs(less-8)
Developing NES game (cc65) 03 and VRAM buffer with C language
Let Arduino support nuvotom Xintang
聚变云原生,赋能新里程 | 2022 开放原子全球开源峰会云原生分论坛圆满召开