简体   繁体   中英

Convert System::String^% to std::string&

I have a C++ function which takes a std::string& and the string is changed within this function.

I have a CLR function which is passed a System::String^% . I want to be able to pass the CLR string tracking reference to the C++ function and have it change accordingly.

So far I have something like this but it seems quite ugly:

void test(System::String^% x)
{
    pin_ptr<System::String^> x_ptr = &x;
    std::string x_cpp = msclr::interop::marshal_as<std::string>(*x_ptr);
    x_cpp = "qwerty"; //in real code this string is passed to function and changed
    x = gcnew System::String(x_cpp.c_str());
}

is there a more elegant way to do this?

For the first: Because the marshal_as method is declared as taking a System::String^ const & , you can't pass a tracking reference directly. (If there's a cast you can do, I can't figure out what it would be.) However, you can copy x to a regular local variable, and pass that to marshal_as . This eliminates the pin_ptr, which is a good thing.

For the second: Use the same conversion method for the second conversion as the first. Unless you have a special reason to do it differently, marshal_as is probably the best way to handle these conversions.

void otherFunction(std::string& x_cpp)
{
    x_cpp = "qwerty";
}

void test(System::String^% x)
{
    System::String^ x_not_tracking_ref = x;
    std::string x_cpp = msclr::interop::marshal_as<std::string>(x_not_tracking_ref);
    otherFunction(x_cpp);
    x = msclr::interop::marshal_as<System::String^>(x_cpp);
}

int main(array<System::String ^> ^args)
{
    System::String^ foo = "asdfgh";
    Debug::WriteLine(foo);
    test(foo);
    Debug::WriteLine(foo);

    return 0;
}

Output:

asdfgh
qwerty

Basically, I don't think so. I would tend to try and release the pin_ptr as soon as possible. So something like:

std::string string_from_string(System::String^% x)
{
    pin_ptr<System::String^> x_ptr = &x;
    return msclr::interop::marshal_as<std::string>(*x_ptr);
}

void test(System::String^% x)
{
    auto x_cpp = string_from_string(x);
    x_cpp = "qwerty";//in real code this string is passed to function and changed
    x = gcnew System::String(x_cpp.c_str());
}

(Names and syntax all approximate. You might want to write a string_from_string in the reverse direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM