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. Power OJ 2605 SPFA+dp思想

    题目链接[https://www.oj.swust.edu.cn/problem/show/2605] 题意:给出包含N(N <= 5000)个点M条边的有向图,然后求1 - N在满足距离小于T ...

  2. 洛谷.4512.[模板]多项式除法(NTT)

    题目链接 多项式除法 & 取模 很神奇,记录一下. 只是主要部分,更详细的和其它内容看这吧. 给定一个\(n\)次多项式\(A(x)\)和\(m\)次多项式\(D(x)\),求\(deg(Q) ...

  3. 【BZOJ】1415: [Noi2005]聪聪和可可【期望】【最短路】【记忆化搜索】

    1415: [Noi2005]聪聪和可可 Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 2335  Solved: 1373[Submit][Stat ...

  4. bzoj 3306

    以1号节点为根,弄出DFS序,我们发现,对于一个询问:(rt,u),以rt为根,u节点的子树中的最小点权,我们可以根据rt,u,1这三个节点在同一条路径上的相对关系来把它转化为以1为根的在DFS序上的 ...

  5. 4、Redis中对List类型的操作命令

    写在前面的话:读书破万卷,编码如有神 -------------------------------------------------------------------- ------------ ...

  6. Codeforces Round #234 (Div. 2) B. Inna and New Matrix of Candies SET的妙用

    B. Inna and New Matrix of Candies time limit per test 1 second memory limit per test 256 megabytes i ...

  7. PHP运行时强制显示出错信息

    调试很重要 error_reporting(E_ALL); ini_set('display_errors', '1'); 将出错信息输出到一个文本文件 ini_set('error_log', di ...

  8. ASP.NET 构建高性能网站 第2篇

    前言:在对ASP.NET网站进行优化的时候,往往不是只是懂得ASP.NET就足够了的. 在优化的过程中,一般先是找出问题可能存在的地方,然后证明找出的问题就是要解决的问题,确认之后,在进行一些措施.系 ...

  9. JVM监控启动参数

    服务端: JVM监控启动参数 -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=52001 -Dcom.sun.ma ...

  10. HDU 4597 Play Game (DP,记忆化搜索)

    Play Game Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)Total S ...