Get the App
SLTechnology News&Howtos  ›  Development  › 

How to convert between arrays of C # structures

Shulou Source: shulou.com Published: 2022-06-02 08:40:17 09月26日 Update

This article mainly explains "how to convert between C# structure arrays". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn "how to transform between C# structure arrays"!

Conversion between C # structure arrays: when writing C#TCP communication programs, only byte arrays can be sent when sending data. It is troublesome to deal with, and can be implemented in the following ways:

(1) the definition of C# structure array conversion:

/ / Namespace using System.Runtime.InteropServices; / / Note that this attribute cannot be less than [StructLayoutAttribute (LayoutKind.Sequential, CharSet=CharSet.Ansi,Pack=1)] struct TestStruct. {public int c; / / string. SizeConst is the * length of the string [MarshalAs (UnmanagedType.ByValTStr, SizeConst = 256)] public string str. / / int array. SizeConst represents the number of arrays. Before converting to / / byte array, the array must be initialized and then used. The length of the array initializing / / must be the same as that of SizeConst, for example, test = new int [6]; [MarshalAs (UnmanagedType.ByValArray, SizeConst = 6)] public int [] test;}

(2) the structure-to-byte array of C # structure array conversion:

/ * * / structure to byte array / structure to be converted / converted byte array public static byte [] StructToBytes (object structObj). {/ / get the size of the structure int size = Marshal.SizeOf (structObj); / / create the byte array byte [] bytes = new byte [size] / / allocate the memory space of the structure size IntPtr structPtr = Marshal.AllocHGlobal (size); / / copy the structure to the allocated memory space Marshal.StructureToPtr (structObj, structPtr, false); / / copy the memory space to the byte array Marshal.Copy (structPtr, bytes, 0, size); / / release the memory space Marshal.FreeHGlobal (structPtr); / / return the byte array return bytes;}

The problem of C # structure array conversion is introduced to you here. I hope it will be helpful for you to learn and understand the C # structure array conversion.

Thank you for your reading. the above is the content of "how to convert between C# structure arrays". After the study of this article, I believe you have a deeper understanding of the problem of how to transform between C# structure arrays. The specific use also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Arrays structures caches space memory learning questions content size characters strings length allocation consistency number that is attributes ideas situations data Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Huawei vpn macOS MariaDB