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

相关推荐
落寞的星星1 小时前
这个对象就包含了已经转换好的DFA和各种词法分析器运转所需要的参数。下一步,我们就可以用ScannerInfo对象创建出Scanner对象,请看下面的代码:
开发语言·c#
聪慧的水蜜桃4 小时前
【YFIOs】用C#开发硬件之设备上云
开发语言·c#
hixiong12310 小时前
TensorRT转换工具分享
人工智能·计算机视觉·ai·c#
莫生灬灬11 小时前
DY联系人聊天Web面板支持获取联系人/聊天记录/发送消息
前端·chrome·websocket·c#
逝水无殇13 小时前
C# 多态性详解
开发语言·后端·c#
逝水无殇13 小时前
C# 继承(Inheritance)详解
开发语言·后端·c#
asdzx6715 小时前
C# 通过模板生成 Word 文档:文本与图片占位符替换完整攻略
开发语言·c#·word
影寂ldy16 小时前
C# 泛型协变与逆变
windows·microsoft·c#
F20226974861 天前
西门子 PLC 与 C# 通信
开发语言·c#
吴可可1231 天前
C#实现CAD框选闭合图元外偏移1毫米
c#