Yifan wrote:
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(Sys tem::String * str)
{
if (str == 0)
{
return(std::str ing());
}
System::IntPtr
ptr(System::Run time::InteropSe rvices::Marshal ::StringToHGlob alAnsi(str));
std::string ret(static_cast <const char *>(static_cast< void *>(ptr)));
System::Runtime ::InteropServic es::Marshal::Fr eeCoTaskMem(ptr );
return(ret);
}
System::String * ToNetString(con st std::string & ss)
{
if (ss.empty())
{
return(new System::String( S""));
}
System::IntPtr ptr(static_cast <System::IntPtr >(static_cast<v oid
*>(const_cast<c har *>(ss.c_str())) ));
System::String *
ret(System::Run time::InteropSe rvices::Marshal ::PtrToStringAn si(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(dlle xport) when the assembly is being built and
__declspec(dlli mport) 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::My Class::ToCppStr ing(x) or
MyNamespace::My Class::ToNetStr ing(y)..