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

相关推荐
我是唐青枫7 小时前
C#.NET 索引器完全解析:语法、场景与最佳实践
c#·.net
FuckPatience11 小时前
C# 使用内存映射文件实现进程间通信
c#
kylezhao201913 小时前
如何在 C# 项目中使用 NLog 进行日志记录
开发语言·c#
小菱形_15 小时前
【C#】IEnumerable
开发语言·c#
爱敲点代码的小哥15 小时前
Directoy文件夹操作对象 、StreamReader和StreamWriter 和BufferedStream
开发语言·c#
CodeCraft Studio16 小时前
Excel处理控件Aspose.Cells教程:使用C#在Excel中创建折线图
java·c#·excel·aspose.cells·excel图表·excel api库·excel折线图
m5655bj16 小时前
C# 在 PDF 文档中添加电子签名
开发语言·pdf·c#
superman超哥17 小时前
仓颉Actor模型的实现机制深度解析
开发语言·后端·python·c#·仓颉
一只蚊子018 小时前
C# WinForms配置Halcon
windows·c#·halcon
阿蒙Amon18 小时前
C#每日面试题-进程和线程的区别
java·面试·c#