且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将C ++ / CLI字符串数组转换为字符串向量

更新时间:2023-02-12 15:44:35

MSDN 提供了有关如何封送数据的一些详细信息。它们还为 msclr :: marshal_as w.r.t提供了一些标准实现。 std :: string

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

cli :: array 稍微复杂一点,这里一般情况的关键是先 pin 数组(这样我们才不会在后面移动它)。对于 String ^ 转换, marshal_as pin 适当的 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.

代码的要旨是:

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