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

相关推荐
weixin_428005309 小时前
C#调用 AI学习从0开始-第3阶段RAG向量数据库-文档切分与入库第15天
人工智能·学习·c#·向量数据库·rag·qdrant·文档切分与入库
心平气和量大福大10 小时前
C#-WPF-布局-Grid
c#·wpf·visual studio
TeamDev10 小时前
JxBrowser 9.3.1 版本发布啦!
java·前端·javascript·c#·混合应用·jxbrowser·浏览器控件
格林威13 小时前
工业相机Chunk功能全解析:图像嵌入时间戳、编码器元数据(附堡盟C#代码)
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机
Vae_Mars13 小时前
C#中多线程异步操作的方法-Parallel.ForEachAsync
开发语言·c#·php
Arbori_2621513 小时前
Rider 调试 VisionMaster C# 用户脚本
c#·visionmaster
暗暗别做白日梦17 小时前
Pulsar 消息同步机制
c#·linq
海盗123417 小时前
微软技术周报——2026-07-22
microsoft·c#·.net
海盗123417 小时前
微软技术日报 ——2026-07-21
microsoft·c#·.net