C++/CLI 字符串转换
我发现这段非常好的代码将字符串转换为 System:String^
,如下所示:
System::String^ rtn = gcnew String(move.c_str()); // 'move' here is the string
我将 rtn 传递回 C# 程序。不管怎样,在这段代码所在的函数内部,我传入了一个System::String^
。我还找到了一些使用以下代码将 System:String^
转换为字符串的代码:
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' 作为字符串。
然而,这似乎比使用 gcnew 进行其他转换需要更多的工作。所以,最后我的问题是,是否有什么东西可以使用与 gcnew 方式类似的方式将 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
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);
Now I can use 'ch' as a string.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 VC++ 的封送库:C++ 封送概述
Use VC++'s marshaling library: Overview of Marshaling in C++
这可能很有用:
不要忘记使用命名空间 System::Runtime::InteropServices;
this could be useful:
don't forget
using namespace System::Runtime::InteropServices;