Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting System::String to Const Char * [duplicate]

I am using Visual C++ 2008's GUI creator to make a user interface. When a button is clicked, the following function is called. The content is supposed to create a file and name the file after the contents of the textbox "Textbox' with '.txt' at the end. However, that leads me to a conversion error. Here is the code:

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

Here is the error:

error C2664: 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream(const char *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'System::String ^' to 'const char *'

How can I do a conversion to allow this to go through?

like image 280
Reznor Avatar asked Jan 19 '10 12:01

Reznor


People also ask

How to convert c++ string to const char*?

You can use the c_str() method of the string class to get a const char* with the string contents.

How to convert string into char* in Cpp?

The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.

What is the difference between const char * and string?

string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.


2 Answers

I would use marshalling:

//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);

But note that you then use just Ansi strings. If you need unicode support you can use the widechar STL class wofstream and PtrToStringChars (#include <vcclr.h>) to convert from System::String. In that case you do not need to free the pinned pointer.

like image 183
jdehaan Avatar answered Oct 11 '22 13:10

jdehaan


It's simple!

As you're using managed C++, use the include and operate like:

#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
}
like image 37
Timber Wolf Avatar answered Oct 11 '22 15:10

Timber Wolf