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. 工作中怎么解决bug

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 1,看日志 2,看日志解决不了,断点调试 3,网络搜索.

  2. MyTalkStuffHomeIcon-2

    圆形.高清头像素材专用-2

  3. 技能树升级——Chrome Headless模式 - 全栈客栈 - SegmentFault

    技能树升级--Chrome Headless模式 - 全栈客栈 - SegmentFault TNPM

  4. QT 安装 4.8.7 on solaris 10

    1.  下载 QT 4.8.7: http://download.qt.io/official_releases/qt/4.8/4.8.7/qt-everywhere-opensource-src-4 ...

  5. 常见 core dump 原因分析signal 11 - SIGSEGV

    signal 6 - SIGABRT free 多次 char *p = malloc(100); free(p); free(p); fclose 多次 // fclose 内部调用 free FI ...

  6. C# iTextSharp 生成 PDF

    使用iTextSharp在Asp.Net中操作PDF系列文章 目录 http://www.cnblogs.com/CareySon/category/332146.html 实战 iTextSharp ...

  7. 使用C#中的out关键字,用世界杯演绎

    今年的世界杯好看至极,充满着故事性.戏剧性.无论你平常踢不踢球,也不管你是否懂球,你总能从中获得些许的情感释放.世界杯似乎超越了足球本身,成为世界各地人们的"情感总和",一场场比赛 ...

  8. 音频视频解决方案:GStreamer/ffmpeg/ffdshow/directshow/vfw

    音频视频编程相关:GStreamer/ffmpeg/directshow/vfw linux和window下几种流行的音频视频编程框架作一个总结,防止自己迷惘,免于晕头转向. 一.GStreamer ...

  9. OpenShift上部署Redis主从集群

    客户有部署有状态服务的需求,单机部署模式相对简单,尝试一下集群部署. 关于Redis的master,slave 以及sentinal的架构和作用不提,有兴趣可以参考之前的博客 https://www. ...

  10. UT-Austin大学在Image search and large-scale retrieval方面的一系列papers

    WhittleSearch: Interactive Image Search with Relative Attribute Feedback.  A. Kovashka, D. Parikh, a ...