Maileen wrote:
How can we convert string^ to String or to LPCWSTR ?
Unmanaged to Managed:
------------------------------------
char* su;
String^ sm = gcnew String(su);
wchar_t* su;
String^ sm = gcnew String(su);
std::string su;
String^ sm = gcnew String(su.c_str ());
std::wstring su;
String^ sm = gcnew String(su.c_str ());
Managed to Unmanaged:
------------------------------------
Wide string version:
String^ sm = "Hello";
pin_ptr<wchar_t > pu = PtrToStringChar s(sm);
// PtrToStringChar s is an inline function in vcclr.h, and it returns
// a raw pointer to the internal representation of the String.
// After pinning "p", it can be passed to unmanaged code:
wchar_t* su = pu;
// when "pu" goes out of scope, "su" becomes invalid!
Ansi (8-bit) version:
ScopedHGlobal s_handle(Marsha l::StringToHGlo balAnsi(sm));
char* su = s_handle.c_str( );
// when "s_handle" goes out of scope, "su" becomes invalid!
Where ScopedHGlobal is a helper class written by myself:
using namespace System::Runtime ::InteropServic es;
public ref class ScopedHGlobal
{
public:
ScopedHGlobal(I ntPtr p) : ptr(p) { }
~ScopedHGlobal( ) { Marshal::FreeHG lobal(ptr); }
char* c_str() { return reinterpret_cas t<char*>(ptr.To Pointer()); }
private:
System::IntPtr ptr;
};
Tom