将System :: String转换为Const Char *

时间:2010-01-19 12:16:08

标签: c++ string char const

我正在使用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 *'

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

6 个答案:

答案 0 :(得分: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);

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

答案 1 :(得分: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
}

答案 2 :(得分:3)

#include <string>
#include <iostream>
#include <atlbase.h>
#include <atlconv.h>
#include <vcclr.h>

using namespace System;

int main(array<System::String ^> ^args)
{
    String^ managedStr = gcnew String(L"Hello, Managed string!");
    //If you want to convert to wide string
    pin_ptr<const wchar_t> wch = PtrToStringChars(managedStr);
    std::wstring nativeWstr(wch);
    //if you want to convert to std::string without manual resource cleaning
    std::string nativeStr(CW2A(nativeWstr.c_str()));
    std::cout<<nativeStr<<std::endl;
    Console::WriteLine(L"Hello World");
    return 0;
}

答案 3 :(得分:2)

谢谢jdehaan。我很少修改代码以将其用于我的'普通'System :: String's。

void MarshalNetToStdString(System::String^ s, std::string& os)
{
    using System::IntPtr;
    using System::Runtime::InteropServices::Marshal;

    const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer( );
    os = chars;
    Marshal::FreeHGlobal(IntPtr((void*)chars));
}

如果你想转换System:String - &gt;这就是这种方法。 STD:字符串

答案 4 :(得分:0)

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

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

示例:

CString(Textbox->Text)

在您的具体案例中:

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

答案 5 :(得分:0)

MSDN中关于字符串转换的文章非常精彩:

http://msdn.microsoft.com/en-us/library/ms235631%28vs.80%29.aspx

有很多样本可以将String转换为不同的类型。

相关问题