[C++] zlatlcv: ATL字符串转换辅助库。能很方便的将UTF-8字符串转为TCHAR等字符串

作者:zyl910

如今,UTF-8字符串的使用频率越来越多了。但是在VC中,不能直接处理UTF-8字符串,得专门去写UTF-8与窄字符串、宽字符串、TCHAR字符串相互转换的代码。不仅费时费力,而且稍不留心就容易造成内存泄露问题。于是我便想专门编写个库来解决UTF-8字符串编码问题。

特性——
支持 TCHAR,能随时切换项目字符集配置。
兼容 32位(x86)与64位(x64)Windows环境。
兼容 VC2005 及更高版本的 VC。


一、设计思路

ATL中的字符串转换宏用起来很方便,于是我打算参考它,做一套字符串转换宏。

转换宏的命名规则——

C<SourceType>2[C]<DestinationType>[EX]

<SourceType>、<DestinationType>:字符串类型。可以为 A(char), W(wchar_t), T(TCHAR), U8(UTF-8) 。
[C]:是否是常量。
[EX]:是不是加强版。即是否具有 t_nBufferLength 这样的模板参数。

例如常用转换宏有——

CU82A: 将 UTF-8字符串 转为 窄字符串。
CA2U8: 将 窄字符串 转为 UTF-8字符串。
CU82W: 将 UTF-8字符串 转为 宽字符串。
CW2U8: 将 宽字符串 转为 UTF-8字符串。
CU82T: 将 UTF-8字符串 转为 TCHAR字符串。
CT2U8: 将 TCHAR字符串 转为 UTF-8字符串。


二、范例代码

范例代码——

#include <stdio.h>
#include <locale.h>
#include <tchar.h>

#include "zlatlcv.h"


// "Welcome": English, Traditional Chinese, Japanese, Korean.
const char* psa = "A_Welcome_歡迎_ようこそ_환영.";    //!< UTF-8 string( Auto. File used UTF-8 encoding).
const wchar_t* psw = L"W_Welcome_u6B61u8FCE_u3088u3046u3053u305D_uD658uC601.";    //!< Wide char string.

int _tmain(int argc, _TCHAR* argv[])
{
    // init.
    setlocale(LC_ALL, "");    // 使用客户环境的缺省locale.

    // title.
    _tprintf(_T("zlatlcv v1.0 (%dbit)
"), (int)(8*sizeof(int*)));
    _tprintf(_T("sizeof(wchar_t): %d
"), (int)(sizeof(wchar_t)));
    _tprintf(_T("sizeof(TCHAR): %d
"), (int)(sizeof(TCHAR)));
    _tprintf(_T("
"));

    // printf.
    fflush(stdout);
    printf("printf A:	%s
", psa);
    printf("printf W:	%ls
", psw);
    printf("
");

    // UTF-8 to string (UTF-8 转 各种字符串).
    //CA2AZ psaa(psa, CP_UTF8, 0);
    CU82A psaa(psa);
    CU82W psaw(psa);
    printf("printf A from UTF-8:	%s
", psaa);
    printf("printf W from UTF-8:	%ls
", psaw);
    printf("
");

    // string to UTF-8 (各种字符串 转 UTF-8).
    CA2U8 psau8(psaa);
    CW2U8 pswu8(psaw);
    fflush(stdout);
    printf("printf UTF-8 from A:	%s
", psau8);
    printf("printf UTF-8 from W:	%s
", pswu8);

    // _tprintf.
    CA2CT psat(psa);
    CW2CT pswt(psw);
    CU82T psu8t(psa);
    fflush(stdout);
    _tprintf(_T("_tprintf A:	%s
"), psat);
    _tprintf(_T("_tprintf W:	%s
"), pswt);
    _tprintf(_T("_tprintf U8:	%s
"), psu8t);

    return 0;
}


运行效果——

源码下载——
https://github.com/zyl910/zlatlcv

原文地址:https://www.cnblogs.com/zyl910/p/zlatlcv.html