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

相关推荐
MaoziShan13 小时前
CMU Subword Modeling | 09 Lexemes, or What Dictionaries Know about Morphology
开发语言·人工智能·机器学习·语言模型·自然语言处理·c#
游乐码13 小时前
c#选择排序
c#·排序算法
listhi52015 小时前
基于C#实现动态人脸检测
开发语言·c#
rabbitlzx18 小时前
《Async in C# 5.0》第十四章 深入探讨编译器对于async的转换
java·开发语言·c#·异步·asynchronous
智商偏低19 小时前
unity 如何渲染大场景
c#
光泽雨21 小时前
单例模式代码理解
开发语言·c#
软泡芙1 天前
【C#】一个原始的标准蓝牙心率血氧服务的数据:字节数组byte[]有5个数据分别的0、0、240、0、240,转成IEEE 11073 SFLOAT
c#
gc_22991 天前
C#学习调用OpenMcdf模块解析ole数据的基本用法(2)
c#·ole·openmcdf·offvis软件
bugcome_com2 天前
C# 变量详解(从入门到掌握)
c#
kylezhao20192 天前
C#中如何防止序列化文件丢失和损坏
c#