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

相关推荐
kylezhao201929 分钟前
C#中 Invoke、begininvoke、InvokeRequired的详细讲解和三者之间的区别
开发语言·c#
光泽雨43 分钟前
c#反射复习
c#
yongui478341 小时前
基于C#实现视频文件解封装与媒体流读取方案
开发语言·c#·媒体
游乐码20 小时前
c#万物之父装箱拆箱
开发语言·c#
GIS程序猿20 小时前
批量出图工具,如何使用C#实现动态文本
开发语言·arcgis·c#·arcgis插件·gis二次开发
量子物理学21 小时前
三、C#高级进阶语法——特性(Attribute)
java·算法·c#
量子物理学21 小时前
四、C#高级进阶语法——委托(Delegate)
开发语言·c#
bepeater12341 天前
Laravel9.X核心特性全面解析
c语言·c++·c#·php
lpfasd1231 天前
Markdown 导出 Word 文档技术方案
开发语言·c#·word
m5655bj1 天前
通过 C# 将 PPT 文档转换为 HTML 格式
c#·html·powerpoint