将 TCHAR 类型的字符串转换为 WCHAR 类型的字符串的参考代码

///////////////////////////////////////////////////////////////////////////////
// Convert a TCHAR string to WCHAR string.
// Caller must release the memory of pwszOutput by calling delete[] pwszOutput.
///////////////////////////////////////////////////////////////////////////////
HRESULT ConvertTCharToWChar( TCHAR * ptszInput, WCHAR ** pwszOutput )
{
    int cchOutput = 0;
   
    if( NULL == ptszInput || NULL == pwszOutput )
    {
        return( E_INVALIDARG );
    }

    //
    // Get output buffer size
    //
#ifdef UNICODE
    cchOutput = wcslen( ptszInput ) + 1;
#else //UNICODE
    cchOutput = MultiByteToWideChar( CP_ACP, 0, ptszInput, -1, NULL, 0 );
    if( 0 == cchOutput )
    {
        return( HRESULT_FROM_WIN32( GetLastError() ) );
    }
#endif // UNICODE

    *pwszOutput = new WCHAR[ cchOutput ];
    if( NULL == *pwszOutput)
    {
        return( E_OUTOFMEMORY );
    }

#ifdef UNICODE
    wcsncpy( *pwszOutput, ptszInput, cchOutput );
#else //UNICODE
    if( 0 == MultiByteToWideChar( CP_ACP, 0, ptszInput, -1, *pwszOutput, cchOutput ) )
    {
        SAFE_ARRAYDELETE( *pwszOutput );
        return( HRESULT_FROM_WIN32( GetLastError() ) );
    }       
#endif // UNICODE

    return( S_OK );
}

posted @ 2011-10-14 10:49  Tbeck  阅读(359)  评论(0编辑  收藏  举报