C#中结构体定义并转换字节数组
作者:野牛程序员:2023-08-04 08:53:35C#阅读 3224
在 C# 中,可以使用结构体来定义自定义的数据类型,并使用 BitConverter.GetBytes() 方法将结构体转换为字节数组,以及使用 BitConverter.ToXXX() 方法将字节数组转换回结构体。下面是一个示例:
using System;
// 定义结构体
struct Person
{
public int Age;
public string Name;
}
class Program
{
static void Main()
{
// 创建结构体实例
Person person = new Person { Age = 30, Name = "John" };
// 结构体转换为字节数组
byte[] byteArray = StructToByteArray(person);
// 字节数组转换为结构体
Person restoredPerson = ByteArrayToStruct<Person>(byteArray);
// 输出结果
Console.WriteLine("Original Person: Age={0}, Name={1}", person.Age, person.Name);
Console.WriteLine("Restored Person: Age={0}, Name={1}", restoredPerson.Age, restoredPerson.Name);
}
// 结构体转换为字节数组
static byte[] StructToByteArray<T>(T structure) where T : struct
{
int size = System.Runtime.InteropServices.Marshal.SizeOf(structure);
byte[] byteArray = new byte[size];
IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
System.Runtime.InteropServices.Marshal.StructureToPtr(structure, ptr, true);
System.Runtime.InteropServices.Marshal.Copy(ptr, byteArray, 0, size);
System.Runtime.InteropServices.Marshal.FreeHGlobal(ptr);
return byteArray;
}
// 字节数组转换为结构体
static T ByteArrayToStruct<T>(byte[] byteArray) where T : struct
{
T structure;
int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
System.Runtime.InteropServices.Marshal.Copy(byteArray, 0, ptr, size);
structure = (T)System.Runtime.InteropServices.Marshal.PtrToStructure(ptr, typeof(T));
System.Runtime.InteropServices.Marshal.FreeHGlobal(ptr);
return structure;
}
}在上述示例中,定义了一个名为 Person 的结构体,其中包含一个整数变量 Age 和一个字符串变量 Name。然后,使用 StructToByteArray() 方法将结构体转换为字节数组,使用 ByteArrayToStruct() 方法将字节数组转换回结构体,并输出结果。
需要注意的是,这种方法对于简单的结构体是有效的,但对于复杂的数据结构或含有非基本数据类型(如指针)的结构体,可能需要使用其他更复杂的序列化和反序列化机制。在处理复杂的数据结构时,可以考虑使用 JSON、XML、Protocol Buffers 或 MessagePack 等序列化库来进行数据的转换。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C++结构体和char数组互相转换
- 下一篇:C++结构体转byte数组
