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

相关推荐
weixin_408099673 小时前
图片去水印 API 接口实战:网站如何实现自动去水印(Python / PHP / C#)
图像处理·人工智能·python·c#·php·api·图片去水印
:mnong5 小时前
Superpowers 项目设计分析
java·c语言·c++·python·c#·php·skills
我是唐青枫5 小时前
C#.NET 分布式事务 深入解析:TCC、Saga、Outbox 与落地取舍
分布式·c#·.net
CSharp精选营6 小时前
.NET 8 性能优化实战:让你的应用起飞
性能优化·c#·.net·技术干货
fie888911 小时前
C# 文件分割与合并工具设计与实现
开发语言·c#
ytttr87312 小时前
C# 读取数据库表结构工具设计与实现
开发语言·数据库·c#
鸽子一号13 小时前
c#笔记之lambda表达式和linq
笔记·c#·linq
qq_3911053414 小时前
TDengine C# 连接示例和授权管理
大数据·数据库·c#·时序数据库·tdengine
a177988771214 小时前
小程序码的生成与获取码中的scene
小程序·c#
无风听海15 小时前
.NET10之C# Target-typed new expression深入解析
windows·c#·.net