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

相关推荐
(initial)15 小时前
B-02. Shared Memory 深度优化:从 Bank Conflict 到 Tensor Core Swizzling
开发语言·c#
fdc201721 小时前
解耦的艺术:用责任链模式构建可插拔的文件处理流水线
c#·.net·责任链模式
bugcome_com21 小时前
【C# 数组详解】Array 定义、初始化、遍历、内存原理与面试高频问题
后端·c#·asp.net
小码编匠1 天前
WPF 如何在 MVVM模式下实现 DataGrid编辑功能
后端·c#·.net
游乐码1 天前
c#扩展方法
开发语言·c#
qq_454245031 天前
基于ECS的工作流编排框架
数据结构·c#
qq_454245032 天前
BuildTemplateGraph 函数深度解析:动态节点图构建的架构设计与核心价值
数据结构·c#
qq_454245032 天前
SkeletonFlow:基于组合子逻辑与范畴论的数据流处理框架
数据结构·c#
游乐码2 天前
c#静态类和静态构造函数
开发语言·c#
net3m332 天前
自动分工 现象时,一共有几种可能得权重组合变化,如何确保这些组合的扫描时的不发生组合爆炸
人工智能·c#·ai编程