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

相关推荐
小金子会发光6 小时前
C# WinForms 手搓 Modbus RTU 调试助手:不依赖第三方 Modbus 库,从 CRC16 到 8 种功能码完整实现
c#·modbusrtu·串口通讯
上海安当技术10 小时前
C/S 桌面软件怎么接 UKey 强认证?C# SDK 与 C 动态库集成 WinForms/Qt/工控实战
c语言·qt·c#
明如正午11 小时前
【C#】跨线程更新进度条_UpdateProgress 方法解析
c#
曹牧13 小时前
C#:`JsonConvert.DeserializeObject`
windows·c#
望天hous13 小时前
C#中masstranist快速入门
开发语言·c#
冷咖啡离 我的笨笨14 小时前
数据去重:通过 C# 删除 Excel 中的重复行
开发语言·c#·excel
鱼听禅17 小时前
C#学习笔记-添加编译参数到程序集自动更新程序编译时间
笔记·学习·c#
不正经学生17 小时前
C语言指针进阶:const 和野指针——给指针加锁,向野指针宣战
c语言·开发语言·c++·算法·c#
czhc114007566318 小时前
# ProcessJob 构造函数 — 语法与概念
c#
用户2986985301419 小时前
无需安装 Excel,也能轻松将 CSV 转为 XLS 或 XLSX
后端·c#·excel