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

相关推荐
我是苏苏2 小时前
C#高级:使用ConcurrentQueue做一个简易进程内通信的消息队列
java·windows·c#
Never_Satisfied4 小时前
C#获取汉字拼音字母方法总结
开发语言·c#
不绝1919 小时前
C#核心:多态
开发语言·c#
橙露10 小时前
C#在视觉检测中的优势:工业智能化转型的利器
开发语言·c#·视觉检测
爱说实话11 小时前
C# DependencyObject类、Visual类、UIElement类
开发语言·c#
TDengine (老段)12 小时前
TDengine C# 语言连接器进阶指南
大数据·数据库·人工智能·物联网·c#·时序数据库·tdengine
a***592612 小时前
C++跨平台开发:挑战与实战指南
c++·c#
leo__52013 小时前
基于C#实现软件注册码注册机制
开发语言·c#·哈希算法
cjp56014 小时前
019.C#管道服务,两软件间用json数据交互
开发语言·c#·json
我的炸串拌饼店1 天前
火山方舟API C#服务类设计解析
c#·调用火山方舟api