Yifan said:
Hi,
Does anybody know how to convert System::String* to char*? I searched
the System::String class members and did not find any. Thanks.
Try these two functions for converting a System::String * to a std::string
and back again:
std::string ToCppString(System::String * str)
{
if (str == 0)
{
return(std::string());
}
System::IntPtr
ptr(System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(str));
std::string ret(static_cast<const char *>(static_cast<void *>(ptr)));
System::Runtime::InteropServices::Marshal::FreeCoTaskMem(ptr);
return(ret);
}
System::String * ToNetString(const std::string & ss)
{
if (ss.empty())
{
return(new System::String(S""));
}
System::IntPtr ptr(static_cast<System::IntPtr>(static_cast<void
*>(const_cast<char *>(ss.c_str()))));
System::String *
ret(System::Runtime::InteropServices::Marshal:
trToStringAnsi(ptr));
return(ret);
}
I put these in a __nogc class in a namespace in a shared assembly and both
are static functions. I then export the class when creating the assembly and
import the class when using the assembly, using a macro which becomes either
__declspec(dllexport) when the assembly is being built and
__declspec(dllimport) otherwise. Since it is a __nogc class, you need to
#include the header file in which the static functions and their __nogc
class are defined. Then to convert from a System::String * to a std::string
or vice-versa, I use the full name, such as:
MyNamespace::MyClass::ToCppString(x) or
MyNamespace::MyClass::ToNetString(y)..