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

相关推荐
格林威3 分钟前
工业相机图像采集处理:从 RAW 数据到 AI 可读图像,附海康相机 C++实战代码
开发语言·c++·人工智能·数码相机·计算机视觉·c#·工业相机
需要点灵感1 小时前
# 从身份证读卡到钉钉同步:C# WinForms企业级应用开发实战
开发语言·c#·钉钉
SunnyDays10111 小时前
使用 C# 实现 Word 转 Excel并保留格式(只需三步)
c#·word 转 excel·docx转xlsx·doc转xlsx·word 表格转 excel
码路星河1 小时前
SpringBoot3实战:优雅实现Word文档动态生成与下载
开发语言·c#·word
Eiceblue1 小时前
通过 C# 读取 Word 表格数据:高效解析 + 导出为 CSV/TXT
开发语言·c#·word
格林威2 小时前
工业相机图像采集处理:从 RAW 数据到 AI 可读图像,堡盟相机 C#实战代码深度解析
c++·人工智能·数码相机·opencv·算法·计算机视觉·c#
夏霞10 小时前
c# signlar 客户端传递参数给服务端配置方法
开发语言·c#
武藤一雄10 小时前
从零构建C# OOP 知识体系
windows·microsoft·c#·.net·.netcore·oop
唐青枫11 小时前
C#.NET ConcurrentStack<T> 深入解析:无锁栈原理、LIFO 语义与使用边界
c#·.net
aini_lovee13 小时前
C# 实现邮件发送源码(支持附件)
开发语言·javascript·c#