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