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

相关推荐
吴可可1234 小时前
C#合并首尾相连多段线实战
算法·c#
钮钴禄·爱因斯晨6 小时前
聚焦操作系统中的PV操作
数据库·算法·系统架构·c#
willhuo6 小时前
# 自动化数据采集技术研究与实现:基于Playwright的抖音网页自动化方案
运维·selenium·c#·自动化·chrome devtools·webview
xiaoshuaishuai87 小时前
C# 实现不掉线的CRM
开发语言·c#
筱璦9 小时前
C#期货分仓、策略交易模拟演示系统(含资源下载)
开发语言·c#·策略模式·量化交易·期货交易
唐青枫9 小时前
C#.NET Task 与 async await 深入解析:底层原理、执行流程与实战误区
c#·.net
公子小六9 小时前
基于.NET的Windows窗体编程之WinForms数据表格
windows·c#·.net·winforms
程序员大辉10 小时前
开源LibreOffice(Office办公套件)下载完整安装教程
开发语言·microsoft·c#
yngsqq10 小时前
运行c#脚本
开发语言·数据库·c#