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

相关推荐
闪电麦坤953 小时前
C#:Time.deltaTime
开发语言·c#
InCerry9 小时前
.NET周刊【3月第3期 2025-03-16】
c#·asp.net·.net
观无11 小时前
C# 扩展方法
开发语言·c#
画个逗号给明天"13 小时前
C#从入门到精通(4)
数据库·c#
观无16 小时前
c#中的virtual方法
开发语言·c#
code bean17 小时前
【C#】ForEach vs foreach
开发语言·c#
OpenSeek18 小时前
【设计模式】面向对象的设计模式概述
设计模式·c#·设计原则
码观天工19 小时前
10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
c#·.net·继承·思维·面相对象
FAREWELL000751 天前
C#核心学习(一)面向过程与面向对象编程---初识类和对象
学习·c#·面向对象
yngsqq1 天前
Visual Studio中创建和配置设置文件(Settings.settings) - 详细步骤指南——待调试
c#