Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert C++/CLI String Array into a vector of strings

I have a parameter in C++/CLI as follows:

array<String^>^ list

I want to be able to convert this into a vector of strings.

How would I go about doing this? Not as good with C++/CLI as I want to be.

like image 947
williamtroup Avatar asked Aug 11 '14 12:08

williamtroup


Video Answer


1 Answers

MSDN provides some detail on how to marshal data. They also provide some standard implementation for msclr::marshal_as w.r.t. std::string.

The cli::array is a little more complex, the key for the general case here is to pin the array first (so that we don't have it moving behind our backs). In the case of the String^ conversion, the marshal_as will pin the String appropriately.

The gist of the code is:

vector<string> marshal_array(cli::array<String^>^ const& src)
{
    vector<std::string> result(src->Length);

    if (src->Length) {
        cli::pin_ptr<String^> pinned = &src[0]; // general case
        for (int i = 0; i < src->Length; ++i) {
            result[static_cast<size_t>(i)] = marshal_as<string>(src[i]);
        }
    }

    return result;
}
like image 165
Niall Avatar answered Nov 10 '22 07:11

Niall