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

相关推荐
rockey62711 小时前
基于AScript的Lua脚本语言发布啦
c#·.net·lua·script·动态脚本
名字还没想好☜13 小时前
Go 的 unsafe.Pointer 实战:零拷贝 []byte↔string 转换与三条铁律
开发语言·后端·golang·go·unsafe
半亩码田14 小时前
【.NET新特性·第11篇】C# 14 字段属性:告别手写 backing field
java·c#·.net
曹牧14 小时前
C#:问号
前端·数据库·c#
少控科技15 小时前
农场设备管理代码(2)
开发语言·c#
唐青枫16 小时前
别再把命令行参数写成一团:C#.NET System.CommandLine 实战详解
c#·.net
hez201017 小时前
让 .NET 11 的泛型虚方法变得更快!
c#·.net·.net core·clr·compiler
宝桥南山18 小时前
Microsoft Agent Framework(.NET) - 尝试一下从MCP Server上获取Agent Skills
ai·微软·c#·aigc·.net·.netcore
少控科技20 小时前
农场设备管理代码(1)
开发语言·c#
椒颜皮皮虾྅1 天前
OpenVINO C# API 3.3.1:支持OpenVINO 2026.3及GenAI增强
人工智能·c#·openvino