c# 拷贝结构体_C#中结构体和字节数组转换实现

本文展示了如何在C#中将结构体(StructDemo)与字节数组进行转换。通过使用`Marshal.SizeOf`计算结构体大小,然后利用`Marshal.StructureToPtr`和`Marshal.PtrToStructure`进行安全地转换操作。
摘要由CSDN通过智能技术生成

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

using System.Runtime.InteropServices;

namespace FileSendClient

{

[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]

struct StructDemo

{

public byte a;

public byte c;

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]

public byte[] b;

public byte d;

public int e;

}

unsafe class Program

{

static void Main(string[] args)

{

StructDemo sd;

sd.a = 0;

sd.d = 0;

sd.c = 0;

sd.b = new byte[3] { 0, 0, 1 };

sd.e = 5;

int size = 0;

//此处使用非安全代码来获取到StructDemo的值

unsafe

{

size = Marshal.SizeOf(sd);

}

byte[] b = StructToBytes(sd,size);

ByteToStruct(b, typeof(StructDemo));

}

//将Byte转换为结构体类型

public static byte[] StructToBytes(object structObj,int size)

{

StructDemo sd;

int num = 2;

byte[] bytes = new byte[size];

IntPtr structPtr = Marshal.AllocHGlobal(size);

//将结构体拷到分配好的内存空间

Marshal.StructureToPtr(structObj, structPtr, false);

//从内存空间拷贝到byte 数组

Marshal.Copy(structPtr, bytes, 0, size);

//释放内存空间

Marshal.FreeHGlobal(structPtr);

return bytes;

}

//将Byte转换为结构体类型

public static object ByteToStruct(byte[] bytes, Type type)

{

int size = Marshal.SizeOf(type);

if (size > bytes.Length)

{

return null;

}

//分配结构体内存空间

IntPtr structPtr = Marshal.AllocHGlobal(size);

//将byte数组拷贝到分配好的内存空间

Marshal.Copy(bytes, 0, structPtr, size);

//将内存空间转换为目标结构体

object obj = Marshal.PtrToStructure(structPtr, type);

//释放内存空间

Marshal.FreeHGlobal(structPtr);

return obj;

}

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值