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

相关推荐
c#上位机7 小时前
halcon刚性变换(平移+旋转)——vector_to_rigid
图像处理·人工智能·计算机视觉·c#·halcon
Miss_SQ8 小时前
Webgl打包后删除StreamingAssets文件夹下多余资源
unity·c#·webgl
小猪快跑爱摄影8 小时前
【AutoCad 2025】【C#】零基础教程(二)——遍历 Entity 插件 =》 AutoCAD 核心对象层级结构
开发语言·c#·autocad
烛阴9 小时前
C# Dictionary 入门:用键值对告别低效遍历
前端·c#
Monkey_Xuan11 小时前
C#中的引用传递和值传递
unity·c#
CreasyChan11 小时前
C# LINQ 深度解析:优缺点与性能陷阱
unity·c#·游戏开发
精神小伙就是猛12 小时前
C# sealed密封 追本溯源
开发语言·c#
雨季66613 小时前
C 语言学习指南:从入门到实战的系统路径
c#
缺点内向17 小时前
如何在 C# 中创建、读取和更新 Excel 文档
c#·.net·excel
c#上位机17 小时前
halcon创建对象数组——concat_obj
图像处理·计算机视觉·c#·halcon