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 byte4 { 1, 2, 3,4 };

IntPtr tempMemoryPointer = Marshal.AllocHGlobal(4);

fixed (byte* converted = by1)

{

CopyMemory(tempMemoryPointer, new IntPtr(converted), 4);

}

byte* p1 = (byte*)tempMemoryPointer.ToPointer();

//此时p0到p3分别为: 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();

//此时p0到p3分别为: 0x44 0x33 0x22 0x11

}

}

测试环境

win7 + VS2022

相关推荐
Scout-leaf5 小时前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6257 小时前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech13 小时前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
2601_962072551 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
m0_547486661 天前
《C#语言程序设计与实践》 全套PPT课件
c语言·c#·c语言程序设计
叶帆1 天前
【YFIOs】用C#开发硬件之设备上云
开发语言·unity·c#
IT方大同1 天前
(嵌入式操作系统)信号量
嵌入式硬件·c#
z落落2 天前
C# FileStream文件流读取文件
开发语言·c#
yngsqq2 天前
排版优化 异形排版
c#
苦学的罐头2 天前
C# 协变与逆变深度解析:为什么 IEnumerable<T> 能转换,而 List<T> 不行?
开发语言·c#·list