简体   繁体   中英

UInt32[] versus UInt32*

Good afternoon all,

I've been working with accessing some external DLLs via the InteropServices.DllImport. I originally settled upon some unsafe code as follows:

internal extern static unsafe void CreateArray(Int32 size, [OutAttribute] UInt32* array);

However, I thought that it might be possible to replace this unsafe code with purely safe code by passing a UInt32 array instead of a pointer. The code changes to

internal extern static void CreateArray(Int32 size, [OutAttribute] UInt32[] array);

which seems to work without any problem. However, I err on the side of caution. Is it possible that the GC may now come along and cause problems? Is there a big difference between passing an array and passing a UInt32 pointer? Are there corner cases I'm missing?

Thanks for your insight,

Giawa

The latter is fine. The P/Invoke layer will pin the managed array in memory while CreateArray is executing, and this approach will require no marshaling, since UInt32[] is a blittable type . This will therefore be just as fast as using a pointer.

With the former declaration you would either have to copy the memory out into a proper managed array, unless you were going to operate on the output entirely through the pointer. And this copying would be more expensive. So, in other words, if you are trying to get a proper managed array out of the call, using the latter syntax will perform better and will require no manual data extraction.

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