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 byte4 { 1, 2, 3,4 };

IntPtr tempMemoryPointer = Marshal.AllocHGlobal(4);

fixed (byte* converted = by1)

{

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

}

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

//此时p0到p3分别为: 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();

//此时p0到p3分别为: 0x44 0x33 0x22 0x11

}

}

测试环境

win7 + VS2022

相关推荐
FuckPatience12 小时前
C# 链表元素的引用地址分析
链表·c#
hoiii18712 小时前
C# Txt/Excel/Access 导入导出工具
开发语言·c#·excel
专注VB编程开发20年12 小时前
TFTP 与FTP核心区别:UDP和TCP
c#·tftp
yi念zhi间13 小时前
C#实现控制台多区域输出
开发语言·c#
2501_9307077813 小时前
使用 C# 在 Excel 中合并并居中单元格
开发语言·c#·excel
feifeigo12313 小时前
C# ADB 安卓设备数据传输工具
android·adb·c#
xiaoshuaishuai813 小时前
C# 逆向分析Privazer
数据库·microsoft·c#
baivfhpwxf202313 小时前
雷赛(Leadshine)EtherCAT 数字 I/O 模块(如 EMC-E5064-8)的状态指示灯(I/O 状态)说明
c#·wpf
JaydenAI14 小时前
[MAF预定义Agent中间件-05]ToolApprovalAgent-摆脱重复审批的烦恼
ai·c#·agent·maf·agent中间件