469,645 Members | 1,725 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,645 developers. It's quick & easy.

convert ^string to string or to LPCWSTR

Hi,

How can we convert string^ to String or to LPCWSTR ?
thx,
Maileen
Nov 17 '05 #1
3 3104
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 = PtrToStringChars(sm);
// PtrToStringChars 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(Marshal::StringToHGlobalAnsi(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::InteropServices;
public ref class ScopedHGlobal
{
public:
ScopedHGlobal(IntPtr p) : ptr(p) { }
~ScopedHGlobal() { Marshal::FreeHGlobal(ptr); }
char* c_str() { return reinterpret_cast<char*>(ptr.ToPointer()); }
private:
System::IntPtr ptr;
};

Tom
Nov 17 '05 #2
You cannot convert String^ to String. It makes no sense.

To access the constant unicode string inside String^:

String^ x = gcnew String ("Hi.");
{
pin_ptr<const wchar_t> pStr = PtrToStringChars (x);
const wchar_t *s = pStr;
} // unpin
Brian

Nov 17 '05 #3
You cannot use stack semantics with String. So you can't have something like
:-

String s;

It always has to be :-

String^ s;

Stack semantics is also not available for array and delegate.

--
Regards,
Nish [VC++ MVP]
"Maileen" <no*****@nospam.com> wrote in message
news:OA**************@TK2MSFTNGP10.phx.gbl...
Hi,

How can we convert string^ to String or to LPCWSTR ?
thx,
Maileen

Nov 17 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Convert TextBox.Text to Int32 Problem | last post: by
4 posts views Thread by Ken Varn | last post: by
9 posts views Thread by Iwan Petrow | last post: by
15 posts views Thread by Yifan | last post: by
2 posts views Thread by Marcelo Muzilli | last post: by
2 posts views Thread by Neo | last post: by
3 posts views Thread by priyanka | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.