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 byte4 { 1, 2, 3,4 };

IntPtr tempMemoryPointer = Marshal.AllocHGlobal(4);

fixed (byte* converted = by1)

{

CopyMemory(tempMemoryPointer, new IntPtr(converted), 4);

}

byte* p1 = (byte*)tempMemoryPointer.ToPointer();

//此时p0到p3分别为: 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();

//此时p0到p3分别为: 0x44 0x33 0x22 0x11

}

}

测试环境

win7 + VS2022

相关推荐
爱吃苹果的日记本14 小时前
数据结构第一课
c语言·数据结构·数据库·学习·c#
唐青枫16 小时前
C#.NET PInvoke 深入解析:封送、内存布局与原生互操作实战
c#·.net
软件黑马王子19 小时前
24.Editor 资源加载:主要作用和基本原理
开发语言·前端框架·c#
慧都小妮子19 小时前
用 Python 批量把 PDF 参考文献排成 MLA 格式:Spire.Doc for Python 实战
python·pdf·c#·spire.doc·mla格式·参考文献排版·pdf批量处理
UIU1141 天前
补码运算与整数溢出(上
学习·c#·补码·补码运算
曹牧1 天前
C#:模态对话框
开发语言·c#
咕白m6251 天前
C# 如何限制 PDF 复制、打印权限?
c#·.net
yume_sibai1 天前
正则表达式完全指南(基础语法 + 实战应用 + 性能优化 + 最佳实践)
开发语言·正则表达式·c#
Nil2081 天前
leetcode 79单词搜索
开发语言·c#
神仙别闹1 天前
基于C#实现(WinForm)文件管理系统
java·开发语言·c#