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

人盡茶涼 提交于 2019-11-27 03:30:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!