我有一个三层应用程序:
>托管的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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。