Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a System::String^ to const char*?

Tags:

char

c++-cli

I'm developing an app in C++/CLI and have a csv file writing library in unmanaged code that I want to use from the managed portion. So my function looks something like this:

bool CSVWriter::Write(const char* stringToWrite);

...but I'm really struggling to convert my shiny System::String^ into something compatible. Basically I was hoping to call by doing something like:

if( m_myWriter->Write(String::Format("{0}",someValueIWantToSave)) )
{
    // report success
}
like image 626
Jon Cage Avatar asked Jul 08 '09 14:07

Jon Cage


People also ask

How do I convert a string to a char in C ++?

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 a const char in C?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.

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

using namespace System::Runtime::InteropServices;
const char* str = (const char*) (Marshal::StringToHGlobalAnsi(managedString)).ToPointer();

From Dev Shed.

like image 97
mcandre Avatar answered Nov 24 '22 19:11

mcandre


As mcandre mentions, Marshal::StringToHGlobalAnsi() is correct. But don't forget to free the newly allocated resource with Marshal::FreeHGlobal(), when the string is no longer in use.

Alternatively, you can use the msclr::interop::marshal_as template to create the string resource and automatically release it when the call exits the resource's scope.

like image 30
Steve Guidi Avatar answered Nov 24 '22 19:11

Steve Guidi