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

C# byte[]、struct、intptr之间的相互转换

1.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);
       }
   }

2.Intptr与byte[]互相转换

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

//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 (方法二)
 byte[] ys = new byte[yLength];
 IntPtr buffer= Marshal.UnsafeAddrOfPinnedArrayElement(ys, 0);

3.struct与Intptr互相转换

以下是MSDN的示例,创建一个托管结构,使用 StructureToPtr 方法将它传输到非托管内存,然后使用 PtrToStructure 方法将它传输回托管内存中:**

using System;
using System.Runtime.InteropServices;

public struct Point
{
    public int x;
    public int y;
}

class Example
{
    static void Main()
    {
        // Create a point struct.
        Point p;
        p.x = 1;
        p.y = 1;
        Console.WriteLine("The value of first point is " + p.x + " and " + p.y + ".");

        // Initialize unmanged memory to hold the struct.
        IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(p));

        try
        {
            // Copy the struct to unmanaged memory.
            Marshal.StructureToPtr(p, pnt, false);

            // Create another point.
            Point anotherP;

            // Set this Point to the value of the 
            // Point in unmanaged memory. 
            anotherP = (Point)Marshal.PtrToStructure(pnt, typeof(Point));

            Console.WriteLine("The value of new point is " + anotherP.x + " and " + anotherP.y + ".");

        }
        finally
        {
            // Free the unmanaged memory.
            Marshal.FreeHGlobal(pnt);
        }
    }
}
  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值