问题
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
}
回答1:
using namespace System::Runtime::InteropServices;
const char* str = (const char*) (Marshal::StringToHGlobalAnsi(managedString)).ToPointer();
From Dev Shed.
回答2:
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.
回答3:
There's a list of what types need which conversion in the overview of marshalling in C++.
来源:https://stackoverflow.com/questions/1098431/how-do-i-convert-a-systemstring-to-const-char