6

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.

1
  • Do you also want to convert the character set from Unicode to the thread locale's character set and encoding (at the time the code is executed)? That could be so much the common case that you wouldn't think about it. However, if the data is NTFS file names (for example), you should keep it in Unicode. Commented Aug 12, 2014 at 16:40

1 Answer 1

5

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Why do you need to pin src array?
@AlexFarber, the code was originally templated for the type in the array, in that case it was needed some the type was unknown and the code had to be sure that it was not moved during conversion. In this case, since there the marshal_as is used, it may not be strictly needed in this case, I would need to recheck that. Conversions from managed to unmanaged requires the managed object to not be moved in memory while the data is copied over.
The pinning is not necessary here, this code makes conventional enumeration of String array. All dirty work is dine by marshal_as, which pins a string internally.
How do you go the other way, meaning how do you go from vector<std::string> to cli::array<String^>^?
@benkey. It should be a loop and a simple marshal_as, the pin or marshal context is only really an issue when going from managed to unmanaged.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.