c++ - 将 String^ 转换为 const char*

标签 c++ string stl c++-cli

已经很长时间没有使用 Windows 窗体了,这是我第一次在 C++ 中使用它。

这是我第一次遇到在数据类型和类对象之后使用 ^ 的情况,例如:

Void Form1::btnConvert_Click(System::Object^  sender, System::EventArgs^  e)

诡异的东西。

我正在尝试调用一个需要指向常量字符串的长指针的函数,因此 const char* 或 LPCSTR。

const char* cPath = txtBoxPath->Text.c_str();

问题是当我尝试从字符串转换时^我收到错误:

error C2228: left of '.c_str' must have class/struct/union
          type is 'System::String ^'
          did you intend to use '->' instead?

所以,现在我有点进退两难了。有什么建议么?也许请教我一些关于这个 ^ 符号的知识,因为我在谷歌搜索时似乎没有找到任何东西。

最佳答案

您可以通过以下方式将 System::String 转换为 std::string:

// Requires:
#include <msclr/marshal_cppstd.h>

auto str = msclr::interop::marshal_as<std::string>(txtBoxPath->Text);

一旦你有了一个std::string,那么c_str()将为你提供const char*:

const char* cPath = str.c_str();

注意,你也可以使用Marshal直接进行转换,即:

IntPtr tmpHandle = Marshal::StringToHGlobalAnsi(txtBoxPath->Text);
char *cPath = static_cast<char*>(tmpHandle.ToPointer());

// use cPath

Marshal::FreeHGlobal(tmpHandle); // Don't use cPath after this...

关于c++ - 将 String^ 转换为 const char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22466148/

相关文章:

javascript - Javascript 中字符串逻辑运算符的用途

c++ - 从函数返回矩阵(作为 vector )

c++ - 了解递归以生成排列

C++ 运算符和参数

c - 在 if 指令中读取 c 中的字符串

c# pad left 到字符串

c++ - STL 列表迭代器不会更新我的对象

algorithm - C++ std::unordered_map 键自定义散列

c++ - 在常数时间内修剪 C++ 字符串

c++ - 函数模板的 typedef 的最佳替代方案?