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

相关推荐
胖纸不争3 小时前
Clasp:一个带插件系统的 .NET 10 命令行工具箱
c#·net core
曹牧12 小时前
C#:数字的定义和表示方式
算法·c#
Young_Gnay14 小时前
.NET 之 WebApi学习笔记 (持续更新)
后端·c#
李高钢14 小时前
WPF MVVM Light 入门:从零到Hello World
c#·wpf
曹牧15 小时前
C#:函数参数指定默认值
开发语言·c#
李高钢16 小时前
WPF MVVM Light(三):RelayCommand 命令与 Messenger 消息
前端·c#·wpf
qq_1508419918 小时前
从CVI(C)到Pyside(python)/Qt(C++)/VS(C#)的一点吐槽
c++·qt·c#
AI刀刀20 小时前
能生成 word 文档的文心在导出时易出现排版错乱,AI 导出鸭精准优化版式,提升文档完整性
人工智能·c#·word·excel·ai导出鸭
曹牧21 小时前
C#:字符串做20位截断
开发语言·c#
离陌在学C#1 天前
C# 事件(Event)详解:从概念到实战
开发语言·c#