已经很长时间没有使用 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/