Reputation: 489
I have a three layered application:
The second layer is used as a layer of communication between c# and native c++.
public class ManagedResult
{
public float[] firstArray;
public float[] secondArray;
}
and the unmanaged class
class UnmanagedResult
{
public:
float* firstArray, secondArray;
int arrayLength;
UnmanagedResult(){};
~UnmanagedResult(){};
}
I have in the second layer the following method of a class wich outputs a managed object:
ManagedResult^ CLIContext::GetResults(){
ManagedResult^ primitiveResult = gcnew ManagedResult();
pin_ptr<int> pFirst = &(primitiveResult->firstArray[0]);
pin_ptr<float> pSecond = &(primitiveResult->secondArray[0]);
UnmanagedResult result =UnmanagedResult();
result.firstArray = pFirst;
result.secondArray = pSecond;
_context->GetResults(result);
return primitiveResult;
}
Here the _context is an object of unmanaged class type which manipulates an object of type UnmanagedResult and affects its content.
This solution works fine. But I want to be able to pass by reference the object and with a third party API to alloc and populate the two members firstArray
and secondArray
.
How can I transfer data then from unmanaged result back to primitiveResult?
Upvotes: 4
Views: 1979
Reputation: 51330
As an unmanaged array is just a pointer to its first item, you need to know the item count.
If you want a managed array, you'll have to create one and copy the data there. You won't be able to create a managed array that points to existing unmanaged memory.
Use System::Runtime::InteropServices::Marshal::Copy
for that:
UnmanagedResult unmanagedResult = GetTheUnmanagedResultSomehow();
ManagedResult^ managedResult = gcnew ManagedResult();
managedResult->firstArray = gcnew array<float>(unmanagedResult.arrayLength);
Marshal::Copy(IntPtr(unmanagedResult.firstArray), managedResult->firstArray, 0, managedResult->firstArray->Length);
// Do the same for secondArray
Upvotes: 1