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

感情迁移 提交于 2019-12-23 10:54:34

问题


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:


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;
}


来源:https://stackoverflow.com/questions/25243149/convert-c-cli-string-array-into-a-vector-of-strings

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