Click here to Skip to main content
15,909,039 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
LPCTSTR string_to_LPCTSTR (string str)
{

// ??

}

i tried to find on web a lot, but didnt found..
Posted

Maybe this[^] will help you.
 
Share this answer
 
v2
Try the documentation[^] for the class you are working with.
 
Share this answer
 
The problem is not to solve really easily, because a PCTSTR comes in two flavors, depending on your compile settings. It can denote a wide character string (16-bit characters) or a so-called multi-byte character string (8-bit characters). std::string on the other hand is always a string of 8-bit characters.

So in the easier case, when your compile settings are "multi-byte characters" it's as simple as

LPCTSTR pStr = str.c_str();


In the other compile setting, for wide characters, a conversion must be done and that requires the allocation of memory for the new 16-bit character string. So you end up doing something like:

CString str2 (str.c_str());
    // note that the CString class know how to convert an 8-bit string
    // into a 16-bit string and does the conversion for you. It also
    // allocates the memory for the 16-bit character string.
LPCTSTR pStr = str2;
    // CString also has a built-in cast to LPTCSTR that let's you easily
    // retrieve a pointer to a null-terminated string


Now, the above method also works with the compile settings for "multi-byte character strings", but the intermediate creation of the CString object represents some unnecessary work in that scenario.

Here is a way that works for both compiler settings and is in both scenarios very efficient.

USES_CONVERSION;
    // put that at the head of your function; it defines one temporary
    // variable used by the A2T macro

LPCTSTR pStr = A2T (str.c_str());
    // A2T is an ATL macro that passes the string just through in
    // 8-bit compiles and converts to 16-bit chars by allocating space
    // on the stack in 16-bit compiles. Note that this temporary space
    // only exists while you are in that same function. If you need
    // it any longer you must copy the string to some space that your
    // allocate on the heap.


See MFC tech note 59 for more details on these ATL macros.

Don't forget that pStr stays only valid as long as you are in that same function!

I hope that gets you some ideas on how to proceed.
 
Share this answer
 
Comments
SoMad 16-Jun-12 22:34pm    
Great answer, +5.

Soren Madsen
nv3 17-Jun-12 4:52am    
Thanks Soren!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900