C# byte[] 如何转换成byte*

目标:将byte[]转成byte*以方便使用memcpy

DllImport("kernel32.dll", EntryPoint = "RtlCopyMemory", CharSet = CharSet.Ansi)

public extern static long CopyMemory(IntPtr dest, IntPtr source, int size);

private void butTemp_Click(object sender, EventArgs e)

{

unsafe

{

byte[] by1 = new byte[4] { 1, 2, 3,4 };

IntPtr tempMemoryPointer = Marshal.AllocHGlobal(4);

fixed (byte* converted = by1)

{

CopyMemory(tempMemoryPointer, new IntPtr(converted), 4);

}

byte* p1 = (byte*)tempMemoryPointer.ToPointer();

//此时p[0]到p[3]分别为: 1 2 3 4

}

}

扩展目标:取int的地址以使用memcpy

private void butTemp_Click(object sender, EventArgs e)

{

unsafe

{

int iTmp = 0x11223344;

IntPtr tempMemoryPointer = Marshal.AllocHGlobal(4);

int* converted = &iTmp;

CopyMemory(tempMemoryPointer, new IntPtr(converted), 4);

byte* p1 = (byte*)tempMemoryPointer.ToPointer();

//此时p[0]到p[3]分别为: 0x44 0x33 0x22 0x11

}

}

测试环境

win7 + VS2022

相关推荐
葛小白19 小时前
C#进阶13:C#全局路径规划算法_A*
c#·路径规划算法·astar算法
时光追逐者12 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 61 期(2025年11.10-11.16)
c#·.net·.netcore
世洋Blog14 小时前
Unity面经-List底层原理、如何基于数组、如何扩容、List存储泛型、List有关在内存中的结构
unity·面试·c#·list
PfCoder15 小时前
C# async / await 用法以及和Task的关系
c#·多线程·winform·async、await
唐青枫19 小时前
.NET Web 应用 Linux 部署全指南:从环境搭建到生产上线
c#·.net
Charles_go1 天前
41、C#什么是单例设计模式
java·设计模式·c#
夏霞1 天前
c# ASP.NET Core SignalR 客户端与服务端自动重连配置指南
开发语言·c#·asp.net
Scout-leaf1 天前
九成九新自用C#入门文档
c#