将System :: String转换为Const Char*

Rez*_*nor 5 c++ string const char

我正在使用Visual C++ 2008的GUI创建器来创建用户界面.单击按钮时,将调用以下函数.内容应该创建一个文件,并在文本框"Textbox"的内容后面加上'.txt'命名文件.但是,这导致转换错误.这是代码:

private: System::Void Button_Click(System::Object^ sender, System::EventArgs^ e) { ofstream myfile (Textbox->Text + ".txt"); myfile.close(); }

这是错误:

错误C2664:'std :: basic_ofstream <_Elem,_Traits> :: basic_ofstream(const char*,std :: ios_base :: openmode,int)':无法将参数1从'System :: String ^'转换为'const char*"

如何进行转换以允许此操作?

jde*_*aan 7

我会用编组:

//using namespace System::Runtime::InteropServices;
const char* str = (const char*)(void*)
       Marshal::StringToHGlobalAnsi(Textbox->Text);
// use str here for the ofstream filename
Marshal::FreeHGlobal(str);
Run Code Online (Sandbox Code Playgroud)

但请注意,然后您只使用Ansi字符串.如果需要unicode支持,可以使用widechar STL类wofstreamPtrToStringChars(#include <vcclr.h>)进行转换System::String.在这种情况下,您不需要释放固定指针.


小智 7

这很简单!

当您使用托管C++时,请使用include并按以下方式操作:

#include <msclr/marshal.h>

...

void someFunction(System::String^ oParameter)
{
   msclr::interop::marshal_context oMarshalContext;

   const char* pParameter = oMarshalContext.marshal_as<const char*>(oParameter);

   // the memory pointed to by pParameter will no longer be valid when oMarshalContext goes out of scope
}
Run Code Online (Sandbox Code Playgroud)


Rud*_*ddy 0

您可以将其转换为 CString,然后向其添加扩展名。

有一个内置的 CString 构造函数可以实现这种转换

例子:

CString(Textbox->Text)
Run Code Online (Sandbox Code Playgroud)

在您的具体情况下:

private: System::Void Button_Click(System::Object^ sender, System::EventArgs^ e) 
{
    ofstream myfile (CString(Textbox->Text) + ".txt"); 
    myfile.close(); 
}
Run Code Online (Sandbox Code Playgroud)