[英]Convert String^ to const char*
很长一段时间没有使用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...
^字符表示托管指针(或引用)。 txtBoxPath :: Text是类型System :: String的引用。 您需要取消引用它才能使用点运算符或仅使用->。
对于System :: String ^到char *,请尝试以下操作:
char* cPath = (char*)Marshal::StringToHGlobalAnsi(txtBoxPath->Text).ToPointer();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.