Convert CString to ANSI string in UNICODE projects

Quick Answer: use an intermediate CStringA.

  • Normally, this is not something that should be done. *It is technically unreliable, unless you can guarantee that the source CString to be converted does not contain any 2-byte characters.
  • This will work fine if you are using the English language without any special 2-byte symbols or accented letters.
  • This article is for educational use, and explains how it can easily be done, without relying on the USES_CONVERSION macro with W2A, or ridiculous WideCharToMultiByte API functions.
  • If you are using a language that actually requires Unicode (Asian languages, etc), or if the source CString contains any 2-byte character, this cannot be done. This is because there is no ANSI equivalent of any 2-byte character.
  • It is the responsibility of the programmer to ensure that the source CString does not contain any 2-byte characters.

    Use intermediate CStringA (highly recommended):

  • Pros: this is the easiest to use.
  • Cons: you cannot specify a code page.

    CString LastNameW(L"Smith");

    CStringA LastNameA(LastNameW);

    FunctionForAnsi(LastNameA.GetString());

  • Or an even simpler example:

    CString LastNameW(L"Smith");

    FunctionForAnsi(CStringA(LastNameW).GetString());

    Here are some other ways that either do not work or are not recommended. I list them here to document things to avoid. What not to do.

    WideCharToMultiByte API function (not recommended):

  • Pros: you can specify the desired code page.
  • Cons: too much code to write, test, debug.

    CString LastNameW(L"Smith");

    int nLen =
    WideCharToMultiByte(CP_ACP,
    0,
    (LPCWSTR)LastNameW,
    -1, NULL, NULL);

    LPSTR lpszA =
    new CHAR[nLen];

    WideCharToMultiByte(CP_ACP,
    0,
    (LPCWSTR)LastNameW,
    -1, lpszA, nLen);

    FunctionForAnsi(lpszA);

    delete[] lpszA;
    // free the string

    W2A ATL 3.0 macros (not recommended):

  • Cons: not safe inside loops.
  • Cons: you cannot specify a code page.

    USES_CONVERSION;

    CString LastNameW(L"Smith");

    FunctionForAnsi(W2A(LastNameW.GetString()));

    CW2A ATL 7.0 conversion template classes (not recommended):

  • There are 3 ways you can use the CW2A template class. Only one of them is the right way.
  • Cons: too difficult to remember the correct usage
  • Cons: too easy to use improperly.

    CString LastNameW(L"Smith");

    CW2A pszA(LastNameW.GetString());
    // this is the right way

    FunctionForAnsi(pszA);

    CString LastNameW(L"Smith");

    FunctionForAnsi(CW2A(LastNameW.GetString()));
    // improper usage, do not do this

    CString LastNameW(L"Smith");

    LPCSTR pszA =
    CW2A(LastNameW.GetString());
    // improper usage, do not do this

    FunctionForAnsi(pszA);

    (LPCSTR)(LPCTSTR) cast:

  • Do not use this!
  • You cannot use (LPCSTR)(LPCTSTR) to cast a CString to LPCSTR in Unicode projects.
  • It does compile, but it does not properly convert the CString to an LPCSTR.
  • The resulting string will either be 0 or 1 length, or filled with garbage characters of unknown length, because the cast just changes the pointer type without any conversion.
  • You end up with a CHAR* pointing to a WCHAR array, a very bad thing.

    CString LastName(L"Smith");

    FunctionForAnsi((LPCSTR)(LPCTSTR)LastName);
    // improper usage, do not to this

    REF:

    ATL String: What's wrong with the USES_CONVERSION macros? How to avoid using them?

    Using MFC MBCS/Unicode Conversion Macros

    ATL and MFC String Conversion Macros

    CString Management

Convert CString to ANSI string in UNICODE projects的更多相关文章

  1. convert \uXXXX String to Unicode Characters in Python3.x

    转换\uXXXX if Python3.x: str.decode no longer exists in 3.x. that']s why Python 3.4: str : AttributeEr ...

  2. CString和string在unicode与非unicode下的相互转换(转)

    原文转自 http://blog.csdn.net/u014303844/article/details/51397556 CString和string在unicode与非unicode下的相互转换 ...

  3. Convert CString to TCHAR

    Quote from: http://vctipsplusplus.wordpress.com/2008/05/21/cstring-to-tchar/ CString is a very usefu ...

  4. CString 与 std::string 相互转化

    MFC中CString 与 std::string 相互转化 CString实际是CStringT, 也就是模板类, 在UNICODE环境下,实际是CStringW, 在多字符集环境下,实际是CStr ...

  5. 【原创】利用typeface实现不同字体的调用显示及String转换为Unicode

    最近工作用到,就写个小demo demo实现从assets中利用typeface调用不同字体,并在editText中显示出来 1.layout中创建activity_main.xml文件 布局代码如下 ...

  6. How to convert any valid date string to a DateTime.

    DateTimeFormatInfo pattern = new DateTimeFormatInfo() { ShortDatePattern = "your date pattern&q ...

  7. mfc中CString转化为string的方法

    LL(1)分析法实验的mfc做到最后因为CString转化为string的问题卡了一个多小时,也是惨,网上各种方法找过都不行.幸亏最后还是找到几行代码搞定了.特此mark一下. USES_CONVER ...

  8. 异常-----Can't convert the date to string, because it is not known which parts of the date variable are in use. Use ?date, ?time or ?datetime built-in, or ?string.\u003Cformat> or ?string(format) built-

    1.错误描述 五月 27, 2014 12:07:05 上午 freemarker.log.JDK14LoggerFactory$JDK14Logger error 严重: Template proc ...

  9. pywinauto: 导入时遇到 "TypeError: LoadLibrary() argument 1 must be string, not unicode"

    pywinauto: 导入时遇到 "TypeError: LoadLibrary() argument 1 must be string, not unicode" 经查询, 看到 ...

随机推荐

  1. luoguP2303 [SDOI2012]Longge的问题 化式子

    求\(\sum \limits_{i = 1}^n gcd(i, n)\) \(\sum \limits_{i = 1}^n gcd(i, n)\) \(=\sum \limits_{i = 1}^n ...

  2. HNOI2018 两天扫雷训练营

    Day -1 不知道干什么 学了下插头DP,随意看了几道题 Day 0 还是不知道干什么 打了一天的模板,1700多行.... 随意学了下回文树 Day 1 上午:各种丢人(好像没人注意) 电脑一开就 ...

  3. Codedforces 1076G Array Game 线段树

    题意 现在cf上看题意真nm麻烦,有道网页翻译和谷歌翻译鬼畜的一匹 两个人在玩一个游戏. 有一个有\(n\)个数序列\(B\),一开始有一个棋子在\(B\)的第一个位置. 双方轮流操作,第一次操作前将 ...

  4. HDU 2553 N皇后问题(深搜DFS)

    N皇后问题 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submi ...

  5. Codeforces Round #296 (Div. 1) B. Clique Problem 贪心

    B. Clique Problem time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...

  6. GIT(5)----常用命令:新分支,切换,删除,远程推送,标签,日志

    常用命令 1.新分支 创建新分支:git branch <branch_name> 创建分支并切换到新的分支上:git checkout -b <branch_name> 2. ...

  7. spring @Transactional注解无效

    <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jd ...

  8. Tasker to stop Poweramp control for the headset while there is an incoming SMS - frozen

    If you usually like to use Poweramp or any other media player to enjoy the music with headset plugge ...

  9. lykchat+zabbix实现微信告警

    http://www.ttlsa.com/zabbix/lykchat-zabbix-wechat-alert/

  10. H5页面开发笔记(react技术栈)

    1.子组件接收父组件的参数,要在子组件的componentDidMount函数中更改当前组件的state,若写在componentWillMount函数中,则会导致初始化界面UI的时候不能得到预期的效 ...