简体   繁体   中英

Passing data from Unmanaged code to managed code

I have a three layered application:

  1. A managed c# layer.
  2. A managed c++/cli layer.
  3. A unmanaged c++ layer.

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?

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

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