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

相关推荐
光泽雨5 小时前
c#中的“跨界找人”
c#
yuan199976 小时前
基于 C# 实现的 Omron HostLink (FINS) 协议 PLC 通讯
开发语言·c#
火星papa7 小时前
C# 任务(Task)的基础实现
c#·任务·task
烛阴10 小时前
Unity资源加载进化论:从AssetBundle到Addressables,一文带你吃透手游资源管理
前端·c#·unity3d
aini_lovee12 小时前
C#与倍福PLC(通过ADS协议)通信上位机源程序实现
开发语言·c#
2501_9307077813 小时前
使用C#代码压平 PDF 表单字段
数据库·pdf·c#
IT知识分享16 小时前
数字上标、下标如何打,6种常用方法详解
开发语言·c#·xhtml
码农学院17 小时前
itextsharp .net中如何设置两个表格的间距设为0,取网站的域名,协议、端口、当前站点目录的地址
开发语言·c#·.net
monkeyhlj18 小时前
Agent Skills简单理解
开发语言·c#
星河耀银海18 小时前
Unity C#入门:变量的定义与访问权限(public/private)
unity·c#·lucene