سؤال

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?

هل كانت مفيدة؟

المحلول

Instead of looping try copying the entire chunk:

Marshal.Copy(pixelData, pixelDataArray, 0, pixelDataLength);

نصائح أخرى

Use Marshal.Copy().

byte[] pixelDataArray = new byte[pixelDataLength];
Marshal.Copy(pixelData, pixelDataArray, 0, pixelDataArray.Length);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top