Question

In C#. I'm working with images obtained from unsafe context. I have an integer with the image size and image pixels pointed by a byte* variable. I would like to copy those pixels into a buffer pointed by an IntPtr. How can I do that?

byte* imgData;        // image data
uint uiDataSize;      // image size
...
IntPtr ptr;
buffer.GetPointer(out ptr);
Was it helpful?

Solution

I don't believe there is a framework method that will work. Marshal.Copy can copy memory into and out of an IntPtr buffer, but it doesn't work with pointers.

Instead you can P/Invoke the native MoveMemory function which copies memory between two pointers.

[DllImport("Kernel32.dll", EntryPoint="RtlMoveMemory", SetLastError=false)]
static extern void MoveMemory(IntPtr dest, IntPtr src, UIntPtr size);
...
byte* imgData;        // image data
uint uiDataSize;      // image size
...
IntPtr ptr;
buffer.GetPointer(out ptr);
MoveMemory(ptr, (IntPtr)imgData, (UIntPtr)uiDataSize);

Yes the size parameter of MoveMemory is UIntPtr not an int because the SIZE_T used in the native code is 32 bits on 32 bit systems and 64 bits on 64 bit systems.

OTHER TIPS

Use System.Runtime.Interopservice.Marshal.Copy, if I remembered correctly. Check the function and you will know how to use it.

Use System.Runtime.Interopservice.Marshal.Copy

using System.Runtime.InteropServices;

byte* imgData;        // image data
uint uiDataSize;      // image size
...
IntPtr ptr;
buffer.GetPointer(out ptr);
// Copy the unmanaged array to a managed array. 
byte[] managedArray = new byte[lengthOfData];
Marshal.Copy(imgData, managedArray, 0, lengthOfData);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top