Main Site Documentation

Returning array from interop code


I’m trying to benchmark native vs managed code using a Bubble Sort algorithm to test memory access.

I’m trying to figure out how to return an array (or pass in an array as a reference) in an interop routine. According to documentation I find, however, that’s not supported.

I went digging through the source code to find native methods that return CLR arrays – but I couldn’t come up with anything to use as an example.

Anyone have any ideas how this is done?


Nope. That article clearly states:

So, like I asked, what is the best way to accomplish this? Does it make sense to allocate a buffer in the CLR side of the project (say, as a field in a class), and then write to it?


Alright, I solved the problem.

I was thinking that whenever an interop routine executed, the passed-in array would be copied into memory and passed by reference to the function.

It looks like that the CLR arrays are passed by reference, so there’s no need to return an array, or pass it in as a C# ref – you can just operate on the array directly, and any changes you make to it will return back to the CLR.

Note that you can’t change arrays dimensions in the native side (not that that’s usually a problem – you can just calculate the new array size in the CLR, allocate it, and then do the heavy-lifting in the interop code)

I can’t mark my own answer as a solution, but if I could, I would!


Here you go! :smiley: