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

相关推荐
anlog9 小时前
ini文件读取,EXE同目录文件读取
c#·ini
rockey6279 小时前
AScript之编译递归函数
c#·.net·script·动态脚本
yue00815 小时前
winform控件篇-按钮
c#
DevOpenClub20 小时前
Markdown、HTML 和 PPT 如何稳定交付:文档转换任务的幂等发布流程
开发语言·前端·c#·html·powerpoint
软件黑马王子20 小时前
3.单例模式问题1:构造函数
开发语言·单例模式·c#
软件黑马王子21 小时前
4.单例模式问题2:重复挂载
开发语言·单例模式·c#
夏霞1 天前
c# 不支持的目标框架 解决方案
开发语言·c#
软件黑马王子1 天前
5.单例模式问题3:多线程问题
单例模式·前端框架·c#
geovindu1 天前
CSharp: Template Method Pattern
开发语言·后端·c#·.net·模板方法模式·行为模式
CSDN_RTKLIB1 天前
SetImpliedSelection
c#