C# byte[]、struct、intptr、byte[]和byte*等的相互转换

struct、byte[]互相转换

//struct转换为byte[]
public static byte[] StructToBytes(object structObj)
{
    int size = Marshal.SizeOf(structObj);
    IntPtr buffer = Marshal.AllocHGlobal(size);
    try
    {
        Marshal.StructureToPtr(structObj, buffer, false);
        byte[] bytes = new byte[size];
        Marshal.Copy(buffer, bytes, 0, size);
        return bytes;
    }
    finally
    {
        Marshal.FreeHGlobal(buffer);
    }
}

//byte[]转换为struct
public static object BytesToStruct(byte[] bytes, Type type)
{
    int size = Marshal.SizeOf(type);
    IntPtr buffer = Marshal.AllocHGlobal(size);
    try
    {
        Marshal.Copy(bytes, 0, buffer, size);
        return Marshal.PtrToStructure(buffer, type);
    }
    finally
    {
        Marshal.FreeHGlobal(buffer);
    }
}

Intptr、byte[]互相转换

//IntPtr转byte[] 
IntPtr y=new IntPtr();
byte[] ys = new byte[yLength];
Marshal.Copy(y, ys, 0, yLength);

//IntPtr转byte[]
private byte[] IntPtrToByte(IntPtr unmanagedMemory, int dataSize)
{
    byte[] managedArray = new byte[dataSize];
   
    try
    {
        // 复制托管数组的内容到非托管内存
        Marshal.Copy(managedArray, 0, unmanagedMemory, managedArray.Length);
    }
    catch (Exception ex)
    {
        // 处理任何异常,比如内存不足等
        Console.WriteLine($"Error: {ex.Message}");
        return managedArray;
    }
    return managedArray;
}


//byte[]转换为Intptr
public static Intptr BytesToIntptr(byte[] bytes)
{
    int size = bytes.Length;
    IntPtr buffer = Marshal.AllocHGlobal(size);
    try
    {
        Marshal.Copy(bytes, 0, buffer, size);
        return buffer;
    }
    finally
    {
        Marshal.FreeHGlobal(buffer);
    }
}

//输入byte[],返回IntPtr ,不使用Marshal创建新的堆,节省内存开销,也避免忘记释放导致的问题
private IntPtr ArrToPtr(byte[] array)
{
   return System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(array, 0);
}

byte[]、byte*互相转换

//从byte*转byte[]
byte[] barr = new byte[10];
byte* bp = (byte*)Marshal.AllocHGlobal(10);
for (int i = 0; i < 10; i++)
    bp[i] = (byte)i;
Marshal.Copy((IntPtr)bp, barr, 0, 10);
PrintArray(barr);
Marshal.FreeHGlobal((IntPtr)bp);


//从byte[]到byte*
byte[] barr = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
byte* bp = (byte*)Marshal.AllocHGlobal(5);
PrintPtr(bp, 5);
Marshal.Copy(barr, 3, (IntPtr)bp, 5);
PrintPtr(bp, 5);
Marshal.FreeHGlobal((IntPtr)bp);

static void PrintPtr(byte* bp,int n)
{
    for(int i=0;i<n;++i)
        Console.Write(bp[i] + " ");
    Console.WriteLine();
}

其他请参考

https://www.cnblogs.com/jhlong/p/5715015.html

https://www.cnblogs.com/castor-xu/p/14719493.html

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C# 中,可以使用 System.Runtime.InteropServices.Marshal 类来实现类似的功能。具体的实现方式如下: ```csharp using System.Runtime.InteropServices; // 定义一个结构体,用于存储打包后的数据 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct PackedData { public byte byte1; public byte byte2; public byte byte3; public byte byte4; public ushort short1; public ushort short2; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] public string str; } // 在代码中使用该结构体进行打包 int len = fw_data.Length; PackedData data = new PackedData { byte1 = 0x03, byte2 = 0x01, byte3 = 0x03, byte4 = 0x00, short1 = (ushort)len, str = fw_data }; byte[] packedBytes = new byte[Marshal.SizeOf(data)]; IntPtr ptr = Marshal.AllocHGlobal(packedBytes.Length); Marshal.StructureToPtr(data, ptr, true); Marshal.Copy(ptr, packedBytes, 0, packedBytes.Length); Marshal.FreeHGlobal(ptr); ``` 上述代码中,首先定义了一个结构体 `PackedData`,用于存储打包后的数据。该结构体中分别包含了 4 个字节、2 个 16 位的短整型和一个长度为 1024 的字符串。其中,字符串使用了 `MarshalAs` 特性来指定长度和编码方式。 在代码中,使用该结构体进行打包时,首先计算出字符串的长度 `len`,然后将各个字段的值赋给结构体实例。接着,使用 `Marshal.SizeOf` 方法获取结构体的大小,创建一个字节数组用于存储打包后的数据。使用 `Marshal.AllocHGlobal` 方法创建一个指向结构体的指针,并且使用 `Marshal.StructureToPtr` 方法将结构体复制到指针所指向的内存中。最后,使用 `Marshal.Copy` 方法将内存中的数据复制到字节数组中,并且使用 `Marshal.FreeHGlobal` 方法释放内存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangnaisheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值