2

I have a ULONG value that contains the address.

The address is basically of string(array of wchar_t terminated by NULL character)

I want to retrieve that string.

what is the best way to do that?

anand
  • 11,071
  • 28
  • 101
  • 159

2 Answers2

7

@KennyTM's answer is right on the money if by "basically of a string" you mean it's a pointer to an instance of the std::string class. If you mean it's a pointer to a C string, which I suspect may be more likely, you need:

char *s = reinterpret_cast<char *>(your_ulong);

Or, in your case:

whcar_t *s = reinterpret_cast<wchar_t *>(your_ulong);

Note also that you can't safely store pointers in any old integral type. I can make a compiler with a 32-bit long type and a 64-bit pointer type. If your compiler supports it, a proper way to store pointers in integers is to use the stdint.h types intptr_t and uintptr_t, which are guaranteed (by the C99 standard) to be big enough to store pointer types.

However, C99 isn't part of C++, and many C++ compilers (read: Microsoft) may not provide this kind of functionality (because who needs to write portable code?). Fortunately, stdint.h is useful enough that workarounds exist, and portable (and free) implementations of stdint.h for compatability with older compilers can be found easily on the internet.

Community
  • 1
  • 1
Chris Lutz
  • 73,191
  • 16
  • 130
  • 183
  • Of course, I probably would have used a C-style cast, but that's because I'm a C programmer at heart. – Chris Lutz Feb 04 '10 at 07:22
  • For practical purposes, `size_t` is as big as a pointer if any integral type is. – Potatoswatter Feb 04 '10 at 07:50
  • @Potatoswatter - For practical purposes, yes, it will, but I actually asked a question a while ago (http://stackoverflow.com/questions/1464174/size-t-vs-intptr-t) about whether this was a kludge or a logical requirement. It turns out that, for _full_ portability, `size_t` is insufficient. Not so much for the present, but into the past, and possibly into the future (because who can predict that?). – Chris Lutz Feb 04 '10 at 08:05
3
string& s = *reinterpret_cast<string*>(your_ulong);
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005