问题描述
我发现这个很好的代码,将字符串转换为 System:String ^
如:
I found this really nice piece of code that converts a string to a System:String^
as in:
System::String^ rtn = gcnew String(move.c_str()); // 'move' here is the string
我将rtn传递回C#程序。无论如何,在这个代码存在的函数内部,我传递一个 System :: String ^
。我还发现一些代码使用以下代码将 System:String ^
转换为字符串:
I'm passing rtn back to a C# program. Anyways, inside the function where this code exists, I'm passing in a System::String^
. I also found some code to convert a System:String^
to a string using the following code:
pin_ptr<const wchar_t> wch = PtrToStringChars(cmd); // 'cmd' here is the System:String
size_t convertedChars = 0;
size_t sizeInBytes = ((cmd->Length + 1) * 2);
errno_t err = 0;
char *ch = (char *)malloc(sizeInBytes);
err = wcstombs_s(&convertedChars,ch, sizeInBytes,wch, sizeInBytes);
现在我可以使用ch作为字符串。
Now I can use 'ch' as a string.
然而,这似乎比使用 gcnew
转换另一种方式更多的工作。所以,最后我的问题是,有什么东西,会将一个 System :: String ^
转换为字符串使用类似的方式与gcnew方式?
This, however, seems to be alot more work than converting the other way using the gcnew
. So, at last my question is, is there something out there that will convert a System::String^
to string using a similar fashion as with the gcnew way?
推荐答案
使用VC ++的编组库:
Use VC++'s marshaling library: Overview of Marshaling in C++
#include <msclr/marshal_cppstd.h>
// given System::String^ mstr
std::string nstr = msclr::interop::marshal_as<std::string>(mstr);
这篇关于C ++ / CLI字符串转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!