2

How can I convert a managed array<String^>^ to std::vector<std::string>. The following code doesnt compile and I can't figure out why. Funny enough, if I use an int for example then it works fine. thanks in advance:

std::vector<std::string> ConvertToUnManaged(array<String^>^ ar)
{
    using System::IntPtr;
    using System::Runtime::InteropServices::Marshal;

    std::vector<std::string> vector(ar->Length);
    Marshal::Copy(ar, 0, IntPtr(&vector[0]), ar->Length);

    return vector;
}
1
  • Why not simply write a loop to do this? That Marshall::Copy seems like overkill to me. Commented Aug 1, 2014 at 3:49

1 Answer 1

3

There is no overload of Marshall::Copy with array of String parameter.

Iterating over the array element and converting one-by-one work.

#include <msclr/marshal_cppstd.h>

std::vector<std::string> ConvertToUnManaged(array<String^>^ ar)
{
    std::vector<std::string> vector(ar->Length);
    for (int i = 0; i < ar->Length; ++i) {
        auto s = ar[i];
        vector[i] = msclr::interop::marshal_as<std::string>(s);
    }
    return vector;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you NetVipC. If you read my question before, nevermind, I figured it out it was a syntax error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.