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

相关推荐
IM1GENIUS1 小时前
.NET高频技术点(持续更新中)
c#·.net
red-fly2 小时前
c#修改ComboBox当前选中项的文本
c#·combobox
bicijinlian5 小时前
.Net HttpClient 概述
c#·.net·httpclient·.net httpclient
码观天工6 小时前
.NET 原生驾驭 AI 新基建实战系列(七):Weaviate ── 语义搜索的智能引擎创新者
ai·c#·.net·向量数据库·weaviate
Zhen (Evan) Wang6 小时前
.NET 8 + Angular WebSocket 高并发性能优化
c#·.net·angular
chenyuhao20247 小时前
链表面试题7之相交链表
数据结构·算法·链表·面试·c#
菜鸟分享录8 小时前
MCP 入门实战:用 C# 开启 AI 新篇章
ai·c#·semantic kernel·mcp
编程乐趣9 小时前
一个用C#开发的记事本Notepads开源编辑器
c#·编辑器·.net
XYR12121220 小时前
C# 参数
c#
oMMh21 小时前
使用C# ASP.NET创建一个可以由服务端推送信息至客户端的WEB应用(2)
前端·c#·asp.net