类型转换

来源:互联网 发布:软件bug 编辑:程序博客网 时间:2024/06/07 12:44
 


//类型char转换为wchar类型
inline bool MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize)
{
    DWORD dwMinSize;
    dwMinSize = MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, NULL, 0);
    if(dwSize < dwMinSize)
    {
        return false;
    }
    MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, lpwszStr, dwMinSize); 
    return true;
}

//类型wchar转换char类型
inline bool WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize)
{
    DWORD dwMinSize;
    dwMinSize = WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,NULL,0,NULL,FALSE);
    if(dwSize < dwMinSize)
    {
        return false;
    }
    WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,lpszStr,dwSize,NULL,FALSE);
    return true;
}

//类型char转换wchar_t类型(wstring)
inline wchar_t* AnsiToUnicode(const char* szStr)
{
    int nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, NULL, 0 );
    if (nLen == 0)
    {
        return NULL;
    }
    wchar_t* pResult = new wchar_t[nLen];
    MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, pResult, nLen );
    return pResult;
}

// 将宽字节wchar_t* 转换单字节char*
inline char* UnicodeToAnsi( const wchar_t* szStr )
{
    int nLen = WideCharToMultiByte( CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL );
    if (nLen == 0)
    {
        return NULL;
    }
    char* pResult = new char[nLen];
    WideCharToMultiByte( CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL );
    return pResult;
}


// 将单字符 string 转换为宽字符 wstring
inline void Ascii2WideString( const std::string& szStr, std::wstring& wszStr )
{
    int nLength = MultiByteToWideChar( CP_ACP, 0, szStr.c_str(), -1, NULL, NULL );
    wszStr.resize(nLength);
    LPWSTR lpwszStr = new wchar_t[nLength];
    MultiByteToWideChar( CP_ACP, 0, szStr.c_str(), -1, lpwszStr, nLength );
    wszStr = lpwszStr;
    delete [] lpwszStr;
}

void TestChangeType()
{
    /* char 转换 wchar   */
    const string sText = "多字节字符串!OK!";
    WCHAR wsText[50];
    memset(wsText,0,sizeof(wsText));
    bool flag = MByteToWChar(sText.c_str(),wsText,sizeof(wsText)/sizeof(wsText[0]));
   
    /*wchar 转换 char */
    wstring Test11 = L"对方东风商店斯蒂芬";
    char array[50];
    memset(array,0,sizeof(array));
    bool glat = WCharToMByte(Test11.c_str(),array,sizeof(array)/sizeof(array[0]));

    wstring ss= AnsiToUnicode( sText.c_str());

    wstring wstext = L"大煞风景看";
    string Text = UnicodeToAnsi( wstext.c_str() );
   
}