在MFC中将字符串转换为LPCTSTR时遇到问题 [英] Getting problems in converting a string to LPCTSTR in MFC

查看:161
本文介绍了在MFC中将字符串转换为LPCTSTR时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

LPCTSTR string_to_LPCTSTR(字符串str)
{

//??

}

我试图在网上找到很多东西,但没有找到..

LPCTSTR string_to_LPCTSTR (string str)
{

// ??

}

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

推荐答案

也许
Maybe this[^] will help you.


尝试
Try the documentation[^] for the class you are working with.


问题并不是很容易解决,因为PCTSTR有两种形式,具体取决于您的编译设置.它可以表示宽字符串(16位字符)或所谓的多字节字符串(8位字符).另一方面,std :: string始终是8位字符的字符串.

因此,在较简单的情况下,当您的编译设置为多字节字符"时,它就像

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();



在其他编译设置中,对于宽字符,必须进行转换,并且需要为新的16位字符串分配内存.所以您最终会做类似的事情:



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



现在,上述方法也可以使用多字节字符串"的编译设置,但是在这种情况下,CString对象的中间创建表示一些不必要的工作.

这是一种适用于两种编译器设置的方法,并且在两种情况下均非常有效.



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.



有关这些ATL宏的更多详细信息,请参见
MFC技术说明59 . .

不要忘了pStr仅在您处于同一功能时才保持有效!

希望您能对如何进行操作有所了解.



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.


这篇关于在MFC中将字符串转换为LPCTSTR时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆