简体   繁体   中英

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?

而不是循环尝试复制整个块:

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

Use Marshal.Copy() .

byte[] pixelDataArray = new byte[pixelDataLength];
Marshal.Copy(pixelData, pixelDataArray, 0, pixelDataArray.Length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM