Link to home
Start Free TrialLog in
Avatar of walterwkh
walterwkh

asked on

LPVOID conversion

How to convert a LPVOID variable to a string ?
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Examples...
// STL string
void foo(LPVOID lpVoid)
{
    // C++
    std::string *pString = reinterpret_cast<std::string *>(lpVoid);
    // C
    std::string *pString = (std::string *) lpVoid;
}
 
// C-String void foo(LPVOID lpVoid)
{
    // C++
    char *pString = reinterpret_cast<char *>(lpVoid);
 
    // C
    char *pString = (char *) lpVoid;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In C++ you should use reinterpret_cast<>() as it is safer than C-style casting.
http://msdn2.microsoft.com/en-us/library/e0w9f63b(VS.80).aspx

Note, then you convert to a pointer of a different type the only safe thing you can do with that pointer is convert it back! Anything else is, at best, non-portable.

All styles of casting are discussed here...
http://msdn2.microsoft.com/en-us/library/x9wzb5es(VS.80).aspx

I hope this help.

-Rx.
Avatar of efn
efn

It depends on what the LPVOID addresses and what kind of string you mean.

If the LPVOID points to some kind of string, you can convert it to a pointer to that kind of string with a cast, as evilrix showed.  A static-cast will work as well as a reinterpret-cast.  If you want a different kind of string, you will have to construct a new string from what the pointer addresses.  This will also require a cast to turn the LPVOID into something you can use.

For example, if the LPVOID points to a C-style null-terminated string and you want a std::string, you can do this:

std::string exvoid(<static-cast>(const char *) lpVoid);
Avatar of walterwkh

ASKER

thanks both evilrix and efn
>> std::string exvoid(<static-cast>(const char *) lpVoid);
std::string exvoid(static_cast<const char *>(lpVoid));
Right, thanks.