C# how to get Byte[] from IntPtr
If it's a byte[]
array:
byte[] managedArray = new byte[size]; Marshal.Copy(pnt, managedArray, 0, size);
If it's not byte[]
, the size parameter in of Marshal.Copy is the number of elements in the array, not the byte size. So, if you had an int[]
array rather than a byte[]
array, you would have to divide by 4 (bytes per int) to get the correct number of elements to copy, assuming your size parameter passed through the callback refers to the number of bytes.
Have you looked into Marshal.Copy?
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.copy.aspx
If you need performance, use it directly:
unsafe { byte *ptr = (byte *)buffer.ToPointer(); int offset = 0; for (int i=0; i<height; i++) { for (int j=0; j<width; j++) { float b = (float)ptr[offset+0] / 255.0f; float g = (float)ptr[offset+1] / 255.0f; float r = (float)ptr[offset+2] / 255.0f; float a = (float)ptr[offset+3] / 255.0f; offset += 4; UnityEngine.Color color = new UnityEngine.Color(r, g, b, a); texture.SetPixel(j, height-i, color); } }}