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

相关推荐
Xin_ye100862 小时前
C# 零基础到精通教程 - 第七章:面向对象编程(入门)——类与对象
开发语言·c#
rockey6272 小时前
AScript异步执行与await关键字
c#·.net·script·eval·expression·异步执行·动态脚本
程序leo源4 小时前
Qt窗口详解
开发语言·数据库·c++·qt·青少年编程·c#
月巴月巴白勺合鸟月半8 小时前
质本洁来还洁去,强于污淖陷文本
c#
Xin_ye100869 小时前
C# 零基础到精通教程 - 第八章:面向对象编程(进阶)——继承与多态
开发语言·c#
asdzx6711 小时前
使用 C# 打印 Excel 文档(详细教程)
c#·excel
伽蓝_游戏12 小时前
第四章:AssetBundle 核心机制与文件结构
unity·c#·游戏引擎·游戏程序
2501_9307077813 小时前
使用C#代码拆分 PowerPoint 演示文稿
开发语言·c#·powerpoint
SenChien13 小时前
C#学习笔记-入门篇
笔记·学习·c#·rider
诙_13 小时前
由C++速通C#
开发语言·c#