Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying unmanaged memory to Managed byte array

I need to read unmanaged memory into a managed byte array.

For this I have an IntPtr reference to unmanaged memory and a length which represents the size of the unmanaged memory that is of interest to me.

I use the following code to read that into a managed byte array.

            byte[] pixelDataArray = new byte[pixelDataLength];
            for (int i = 0; i < pixelDataLength; i++) {
                pixelDataArray[i] = Marshal.ReadByte(pixelData, i);
            }

However this results in very poor performance. Calling this method 1000 times with 256KB of unmanaged memory, takes more than 7 seconds. I think there must be a more efficient way of doing this.

I could not use Marshal.PtrToStructure because i would not know the size of the memory that need to read upfront.

Any ideas on how the performance of this function can be improved?

like image 225
Santhosh Avatar asked Oct 17 '25 15:10

Santhosh


1 Answers

Instead of looping try copying the entire chunk:

Marshal.Copy(pixelData, pixelDataArray, 0, pixelDataLength);
like image 140
Darin Dimitrov Avatar answered Oct 20 '25 04:10

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!