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

相关推荐
玉面小君16 分钟前
从 WPF 到 Avalonia 的迁移系列实战篇6:ControlTheme 和 Style区别
c#·wpf·avalonia
_oP_i6 小时前
WinForms 项目里生成时选择“首选目标平台 32 位导致有些电脑在获取office word对象时获取不到
c#·office
要记得喝水6 小时前
C#某公司面试题(含题目和解析)--1
开发语言·windows·面试·c#·.net
冷冷的菜哥7 小时前
ASP.NET Core文件分片上传
c#·asp.net·asp.net core·文件分片上传
上位机付工9 小时前
2025年了,学C#上位机需要什么条件
c#·上位机·西门子
c#上位机10 小时前
wpf之Border
c#·wpf
almighty2717 小时前
C# 阿里云 OSS 图片上传步骤及浏览器查看方法
c#·图片上传·c# 阿里云 oss·阿里云 oss
Python大数据分析@1 天前
Python 语言有什么奇技淫巧吗?
开发语言·python·c#