M
Marcus Kwok
Hello, I am working on cleaning up some code that I inherited and was
wondering if there is anything wrong with my function. I am fairly
proficient in standard C++ but I am pretty new to the .NET managed C++.
It seems to work fine, but everyone knows that programs with errors can
still appear to "work fine"
I am working with VS .NET 2003; I am unable to upgrade to 2005 at this
time, so I cannot use the newer syntax or features.
This function takes a std::string and converts it to a System::String*.
Here is the original:
System::String*
MarshalStdToNetString(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;
}
Here is my updated version:
// function name is just shorthand for what I will eventually call it
System::String*
std2gc(const std::string& s)
{
return new System::String(s.c_str());
}
Have I oversimplified? Or is all that casting business really needed?
Also, going in the other direction, is this the proper way to convert a
managed System::String* into a std::string? I haven't started trying to
change this one yet:
void
MarshalNetToStdString(System::String* s, std::string& os)
{
using System::IntPtr;
using System::Runtime::InteropServices::Marshal;
const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
wondering if there is anything wrong with my function. I am fairly
proficient in standard C++ but I am pretty new to the .NET managed C++.
It seems to work fine, but everyone knows that programs with errors can
still appear to "work fine"
I am working with VS .NET 2003; I am unable to upgrade to 2005 at this
time, so I cannot use the newer syntax or features.
This function takes a std::string and converts it to a System::String*.
Here is the original:
System::String*
MarshalStdToNetString(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;
}
Here is my updated version:
// function name is just shorthand for what I will eventually call it
System::String*
std2gc(const std::string& s)
{
return new System::String(s.c_str());
}
Have I oversimplified? Or is all that casting business really needed?
Also, going in the other direction, is this the proper way to convert a
managed System::String* into a std::string? I haven't started trying to
change this one yet:
void
MarshalNetToStdString(System::String* s, std::string& os)
{
using System::IntPtr;
using System::Runtime::InteropServices::Marshal;
const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}