简体   繁体   English

将数据从非托管代码传递到托管代码

[英]Passing data from Unmanaged code to managed code

I have a three layered application: 我有一个三层应用程序:

  1. A managed c# layer. 托管c#层。
  2. A managed c++/cli layer. 托管的c ++ / cli层。
  3. A unmanaged c++ layer. 非托管c ++层。

The second layer is used as a layer of communication between c# and native c++. 第二层用作c#与本机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. 在此,_context是非托管类类型的对象,该对象处理UnmanagedResult类型的对象并影响其内容。

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 . 但是我希望能够通过引用传递对象并使用第三方API来分配和填充两个成员firstArraysecondArray How can I transfer data then from unmanaged result back to primitiveResult? 然后如何将数据从非托管结果传输回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: 为此使用System::Runtime::InteropServices::Marshal::Copy

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM