• TCHAR和CHAR类型的互转,string 转lpcwstr


    https://www.cnblogs.com/yuguangyuan/p/5955959.html

    没有定义UNICODE,所以它里面的字符串就是简单用" "就行了,创建工程的时候包含了UNICODE定义,就必须对TCHAR和char进行转换。

    void TcharToChar(const TCHAR * tchar, char * _char)
    {
        int iLength;
        //获取字节长度   
        iLength = WideCharToMultiByte(CP_ACP, 0, tchar, -1, NULL, 0, NULL, NULL);
        //将tchar值赋给_char    
        WideCharToMultiByte(CP_ACP, 0, tchar, -1, _char, iLength, NULL, NULL);
    }
    
    void CharToTchar(const char * _char, TCHAR * tchar)
    {
        int iLength;
        iLength = MultiByteToWideChar(CP_ACP, 0, _char, strlen(_char) + 1, NULL, 0);
        MultiByteToWideChar(CP_ACP, 0, _char, strlen(_char) + 1, tchar, iLength);
    }

    表明 TCHAR 与 WCHAR 属同一类型
    char szA[100];                    // ANSI string buffer
    WCHAR szW[100];            // Unicode string buffer
    // Normal sprintf:all strings are ANSI
    sprintf(szA, "%s","ANSI Str");
    // Converts Unicode string to ANSI
    sprintf(szA,"%S",L"Unicode Str");
    // Normal swprintf:all strings are Unicode
    swprintf(szW,L"%s",L"Unicode Str");
    // Converts ANSI string to Unicode
    swprintf(szW,L"%S", "ANSI Str");
    注意:大写S 和小写s 的使用

     string 转lpcwstr 

        LPCWSTR stringToLPCWSTR(std::string orig)
        {
            wchar_t *wcstring = 0;
            try{
                size_t origsize = orig.length() + 1;
                const size_t newsize = 100;size_t convertedChars = 0;
                if (orig == ""){wcstring = (wchar_t *)malloc(0);
                    mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCATE);
                }
                else{
                    wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(orig.length() - 1));
                    mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCATE);
                }
            }
            catch (std::exception e)
            {}
            return wcstring;
        }
    std::string to_s(LPCWSTR ws)
    {
        DWORD length = WideCharToMultiByte(CP_OEMCP, NULL, ws, -1, NULL, 0, NULL, FALSE);
        std::string result(length, 0);
        WideCharToMultiByte(CP_OEMCP, NULL, ws, -1, &result[0], length, NULL, FALSE);
        result.erase(result.size() - 1, 1);
        return result;
    }
    
    std::wstring to_ws(LPCSTR str)
    {
        int length = MultiByteToWideChar(GetACP(), 0, str, -1, NULL, 0);
        std::wstring result(length, 0);
        MultiByteToWideChar(GetACP(), 0, str, -1, &result[0], length);
        return result;
    }
  • 相关阅读:
    Kotlin扩展深入解析及注意事项和可见性
    Kotlin属性揭秘与延迟初始化特性
    Kotlin伴生对象及其字节码内幕详解
    Kotlin继承与重写重要特性剖析
    Kotlin构造方法详解与初始化过程分析
    Range与面向对象的Kotlin
    Kotlin编译器优化与when关键字详解
    Kotlin基础特性深入讲解
    java读取mysql表的注释及字段注释
    mysql导入导出sql文件
  • 原文地址:https://www.cnblogs.com/xiangtingshen/p/10723546.html
Copyright © 2020-2023  润新知