C#中结构体和字节数组转换实现
最近在使用结构体与字节数组转化来实现socket间数据传输。现在开始整理一下。对于Marshal可以查阅msdn,关于字节数组与结构体转代码如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.IO;
usingSystem.Runtime.InteropServices;
namespaceFileSendClient
{
[StructLayoutAttribute(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=1)]
structStructDemo
{
publicbytea;
publicbytec;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=3)]
publicbyte[]b;
publicbyted;
publicinte;
}
unsafeclassProgram
{
staticvoidMain(string[]args)
{
StructDemosd;
sd.a=0;
sd.d=0;
sd.c=0;
sd.b=newbyte[3]{0,0,1};
sd.e=5;
intsize=0;
//此处使用非安全代码来获取到StructDemo的值
unsafe
{
size=Marshal.SizeOf(sd);
}
byte[]b=StructToBytes(sd,size);
ByteToStruct(b,typeof(StructDemo));
}
//将Byte转换为结构体类型
publicstaticbyte[]StructToBytes(objectstructObj,intsize)
{
StructDemosd;
intnum=2;
byte[]bytes=newbyte[size];
IntPtrstructPtr=Marshal.AllocHGlobal(size);
//将结构体拷到分配好的内存空间
Marshal.StructureToPtr(structObj,structPtr,false);
//从内存空间拷贝到byte数组
Marshal.Copy(structPtr,bytes,0,size);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
returnbytes;
}
//将Byte转换为结构体类型
publicstaticobjectByteToStruct(byte[]bytes,Typetype)
{
intsize=Marshal.SizeOf(type);
if(size>bytes.Length)
{
returnnull;
}
//分配结构体内存空间
IntPtrstructPtr=Marshal.AllocHGlobal(size);
//将byte数组拷贝到分配好的内存空间
Marshal.Copy(bytes,0,structPtr,size);
//将内存空间转换为目标结构体
objectobj=Marshal.PtrToStructure(structPtr,type);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
returnobj;
}
}
}热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下