gpt4 book ai didi

string - C++/CLI 字符串转换

转载 作者:行者123 更新时间:2023-12-02 06:22:54 25 4
gpt4 key购买 nike

我发现这段非常好的代码可以将字符串转换为 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^ 转换为字符串?

最佳答案

使用 VC++ 的编码库:Overview of Marshaling in C++

#include <msclr/marshal_cppstd.h>

// given System::String^ mstr
std::string nstr = msclr::interop::marshal_as<std::string>(mstr);

关于string - C++/CLI 字符串转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6179451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com