How do I convert a cli::array to a native array from native code?

最后都变了- 提交于 2019-12-05 13:12:02

There are two usual approaches:

  1. Perform the marshaling with native code, which requires use of pin_ptr<>:

    boost::shared_array<unsigned char> convert(array<unsigned char>^ arr)
    {
        boost::shared_array<unsigned char> dest(new unsigned char[arr->Length]);
        pin_ptr<unsigned char> pinned = &arr[0];
        unsigned char* src = pinned;
        std::copy(src, src + arr->Length, dest.get());
        return dest;
    }
    
  2. Perform the marshaling with managed code, which requires use of the Marshal class:

    boost::shared_array<unsigned char> convert(array<unsigned char>^ arr)
    {
        using System::Runtime::InteropServices::Marshal;
    
        boost::shared_array<unsigned char> dest(new unsigned char[arr->Length]);
        Marshal::Copy(arr, 0, IntPtr(dest.get()), arr->Length);
        return dest;
    }
    

Generally I would prefer the latter approach, as the former can hinder the GC's effectiveness if the array is large.

Take a look at pin_ptr, it lets you pass address of a managed class to an unmanaged function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!