evilfred
evilfred

Reputation: 2416

Holding onto an array marshalled into C# from C++

I am passing an array of integers from C++ to C#, using a parameter like this in my C# method:

[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] 
UInt32[] myStuff,

When this data arrives in the CLR, I think that "LPArray" indicates that I am working with the pointer from the C++-world directly? So if I want to hold onto this array after the method call is over, should I make a copy of it?

Upvotes: 0

Views: 235

Answers (2)

Bryce Wagner
Bryce Wagner

Reputation: 2650

Calling from unmanaged code into managed code (C++ to C#), the array gets copied into a fully managed array. This array will be freed when the garbage collector notices that nobody has any more references to it, not when the function exits.

But the other direction is more dangerous: If you were going the other direction (C# to C++), it would either: pin the C# array so it won't move, or make a temporary copy of the array into unmanaged memory (which gets freed when the function returns). In either case, it would not be safe to hold onto the array on the C++ side after the function call completes, you'd want to copy the contents to somewhere else.

Upvotes: 0

user541686
user541686

Reputation: 210352

You have to be careful that this is allocated using the same memory allocation mechanisms in both the managed and unmanaged worlds. And even if that's the case, it's just safer to make a copy and work with that.

Note: In your example, the pointer isn't passed by reference, and so the callee can only add to your previous array, not give you a new array. Is that really what you intended?

Upvotes: 1

Related Questions