Search code examples
cc++-cliunmanagedmanagedmanaged-c++

Accessing Unmanaged Array in C++/CLI


My main program is written in C++/CLI (managed). The API for some of my hardware is contained in a .C file. From my main program I call the main() for the unmanaged c code which creates an array and works with the hardware. Once completed it disconnects from the hardware, frees the memory, and returns to the C++/CLI program.

What would be a good way to access (copy) that array from the unmanaged c code to the managed c++?


Solution

  • See How to: Pin Pointers and Arrays; sample code is

    #include <vector>
    #include <algorithm>
    
    #include <msclr/all.h>
    
    using namespace System;
    
    int main(array<System::String ^> ^args)
    {
        constexpr size_t count = 100;
    
        std::vector<int> unmanged_ints;
        for (auto i = 0; i < count; i++)
            unmanged_ints.push_back(i);
    
        auto managed_ints = gcnew cli::array<int>(count);
        cli::pin_ptr<int> pManaged_ = &managed_ints[0];
        int* pManaged = pManaged_;
    
        std::copy(unmanged_ints.cbegin(), unmanged_ints.cend(), pManaged);
    
        return 0;
    }