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

相关推荐
武藤一雄1 天前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore
乱蜂朝王1 天前
使用 C# 和 ONNX Runtime 部署 PaDiM 异常检测模型
开发语言·c#
JosieBook1 天前
【C#】VS中的 跨线程调试异常:CrossThreadMessagingException
开发语言·c#
追雨潮1 天前
BGE-M3 多语言向量模型实战:.NET C# 从原理到落地
开发语言·c#·.net
CheerWWW1 天前
GameFramework——Download篇
笔记·学习·unity·c#
格林威1 天前
ZeroMQ 在视觉系统中的应用
开发语言·人工智能·数码相机·机器学习·计算机视觉·c#·视觉检测
格林威1 天前
工业相机图像采集:如何避免多相机数据混乱
人工智能·数码相机·opencv·机器学习·计算机视觉·c#·视觉检测
武藤一雄1 天前
C#万字详解 栈与托管堆 的底层逻辑
windows·microsoft·c#·.net·.netcore
山檐雾1 天前
C#泛型缓存
缓存·c#
追雨潮1 天前
内存向量检索引擎设计与实现:C# 轻量级 Milvus 替代方案
开发语言·c#·milvus