加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:13:53 所属栏目:百科 来源:网络整理
导读:我有一个三层应用程序: 托管的c#层. 托管c / cli层. 非托管c层. 第二层用作c#和native c之间的通信层. public class ManagedResult{ public float[] firstArray; public float[] secondArray;} 和非托管类 class UnmanagedResult { public: float* firstArr
我有一个三层应用程序:

>托管的c#层.
>托管c / cli层.
>非托管c层.

第二层用作c#和native c之间的通信层.

public class ManagedResult
{
  public float[] firstArray;
  public float[] secondArray;
}

和非托管类

class UnmanagedResult
    {
      public:
         float* firstArray,secondArray;
         int arrayLength;
         UnmanagedResult(){};
         ~UnmanagedResult(){};
    }

我在第二层中有一个类的以下方法输出一个托管对象:

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;

 }

这里_context是非托管类类型的对象,它操纵UnmanagedResult类型的对象并影响其内容.

此解决方案工作正常.但我希望能够通过引用传递对象并使用第三方API来分配和填充两个成员firstArray和secondArray.
如何将数据从非托管结果传输回primitiveResult?

解决方法

由于非托管数组只是指向其第一个项目的指针,因此您需要知道项目计数.

如果需要托管数组,则必须创建一个并在那里复制数据.您将无法创建指向现有非托管内存的托管数组.

使用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,managedResult->firstArray->Length); 

// Do the same for secondArray

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读