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

struct、byte\[\]互相转换

cs 复制代码
//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\[\]互相转换

cs 复制代码
//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*互相转换

cs 复制代码
//从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

相关推荐
IronMurphy19 小时前
AI Agent 学习day4 从 RAG 检索到 Function Call:一文理解大模型问答系统的完整链路
人工智能·学习·c#
爱学习的程序媛19 小时前
C 语言全景指南:从底层原理到工业级实战
c++·c#·c
魔法阵维护师19 小时前
从零开发游戏需要学习的c#模块,第二十九章(经验值与升级系统)
学习·游戏·c#
JaydenAI19 小时前
[MAF预定义ChatClient中间件-04]ReducingChatClient——通过精减对话实施又不丢失基本语义
ai·c#·agent·maf·chatclient管道·对话历史压缩
小满Autumn19 小时前
WPF 进阶:样式、触发器与控件模板
c#·.net·wpf
光泽雨19 小时前
C# 扩展方法(Extension Method)在语法上的核心灵魂。
开发语言·c#
影寂ldy20 小时前
C#Lambda表达式
开发语言·c#
z落落20 小时前
C# 局部方法 + Lambda表达式 + 三大委托和三大委托的区别和手写 Array.Find 底层源码原理(自定义MyArray.Find)
开发语言·c#
weixin_4280053020 小时前
C#调用 AI学习从0开始-第2阶段(Function Calling+工具调用智能体)-第8天Function Calling原理
人工智能·学习·c#·functioncalling
雪豹阿伟21 小时前
12.C# —— 经典排序 +(ArrayList / 泛型 List / Dictionary)
c#·上位机