C# byte[] 如何转换成byte*

简介: 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


相关文章
|
缓存 安全 Java
ByteArray转byte[]的两种方式以及HeapByteBuffer&DirectByteBuffer
将ByteArray转byte[],大部分人第一时间会使用get函数
640 0
|
10月前
|
Java
byte[]转换成String
byte[]转换成String
|
10月前
|
消息中间件 API
无法从“System.ReadOnlyMemory<byte>”转换为“byte[]”
无法从“System.ReadOnlyMemory<byte>”转换为“byte[]”
52 0
将WriteableBitmap转为byte[]
原文:将WriteableBitmap转为byte[] Win8 metro中的操作与之前的版本有所不同,因此作为一个新手,我将自己的一些问题解答记录了下来,希望与大家分享!! 下面是将WriteableBitma...
1075 0
将byte[]转为WriteableBitmap对象
原文:将byte[]转为WriteableBitmap对象 //convert the bytes to WriteableBitmap privateWriteableBitmap BytesToImage(by...
1192 0