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 小时前
告别繁琐的 out 参数:C# 现代元组(ValueTuple)如何重构你的方法返回值
microsoft·c#·asp.net·.net·.netcore
曹牧3 小时前
C#:线程中实现延时等待
开发语言·c#
长不大的小Tom3 小时前
从0开始入门WPF(开发环境搭建)
c#
阿蒙Amon3 小时前
C#常用类库-详解Log4Net
开发语言·c#
唐青枫4 小时前
C#.NET Memory 深入解析:跨异步边界的内存视图与高性能实战
c#·.net
缺点内向5 小时前
.NET办公自动化教程:Spire.XLS操作Excel——导出TXT格式详解
c#·自动化·.net·excel
落叶@Henry5 小时前
C# async 和await 的面试题
开发语言·c#
人工智能AI技术5 小时前
C#接入CodeBuddy CLI实战:在.NET后端集成多AI Provider的全流程拆解
人工智能·c#
地球驾驶员5 小时前
NX二次开发C#-----NXopen测量两个面的投影距离
c#
猹叉叉(学习版)6 小时前
【ASP.NET CORE】 9. 托管服务
数据库·笔记·后端·c#·asp.net·.netcore