[英]Convert System::String^% to std::string&
我有一个采用std::string&
的C ++函数,并且在此函数中更改了字符串。
我有一个CLR函数,该函数通过System::String^%
传递。 我希望能够将CLR字符串跟踪引用传递给C ++函数,并对其进行相应的更改。
到目前为止,我有这样的事情,但看起来很丑陋:
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());
}
有没有更优雅的方法可以做到这一点?
对于第一个:因为marshal_as
方法被声明为采用System::String^ const &
,所以您不能直接传递跟踪引用。 (如果有marshal_as
,我就搞不清楚是什么。)但是,您可以将x
复制到常规局部变量,然后将其传递给marshal_as
。 这消除了pin_ptr,这是一件好事。
对于第二种:对于第二种转换,请使用与第一次相同的转换方法。 除非您有特殊的理由要进行其他marshal_as
, marshal_as
可能是处理这些转换的最佳方法。
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;
}
输出:
asdfgh qwerty
基本上,我不这么认为。 我倾向于尝试尽快释放pin_ptr。 所以像这样:
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());
}
(名称和语法全都近似。您可能想反写一个string_from_string。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.