char和wchar_t的相互转换

来源:互联网 发布:优化服务水平 编辑:程序博客网 时间:2024/05/15 04:07

 基于WIN32 API的转换方法:

 

  BOOL char2wchar_t(const char *str, wstring *wstr)

  {

    

     if(str != NULL) { return FALSE; }

     int nlen = (int)strlen(str);

     int wnlen = (int)MultiByteToWideChar(CP_ACP, 0, (const char *)str, nlen, NULL, 0);

     wchar_t *pBuffer = new wchar_t[wnlen + 1];

     ::MultiByteToWideChar(CP_ACP, 0, str, nlen, pBuffer, wnlen);

     (*wstr) = pBuffer;

      delete pBuffer;

      return TRUE;

  }

 

 

 

 BOOL wchar_t2char(const wchar_t *wstr, string *str)

 {

 

    if (wstr != NULL) { return FALSE; }

     int wnlen = wcslen(wstr);

     int nlen = WideCharToMultiByte(0, 0, wstr, wnlen, NULL, 0, NULL, NULL);

     char *pBuffer = new char[nlen + 1];

     WideCharToMultiByte(0, 0, wstr, wnlen, pBuffer, nlen, NULL, NULL);

    (*str) = pBuffer;

    delete pBuffer;

    return TRUE;

 

}

 

开源库MPEG4IP_mp4v2的转换方法:(只支持字母)

 

static void char2wchar_t(const char *str_char, wchar_t *str_wchar)
{
    int        i, j;
    int        leng;
    char       c;

    leng = strlen(str_char);
    for (i=j=0; i<leng; i++, j++)
    {
        c = str_char[i];
        if (c == 0) {
            str_wchar[j] = '/0';
            break;
        }
        else if (c > 0) {
            str_wchar[j] = (wchar_t)str_char[i];
        }
        else {
            // Currently the non-alphanumeric characters are not supported.
            i++;
        }
    }

    str_wchar[j] = 0;
}

 

 

static void wchar_t2char(const wchar_t *str_wchar, char *str_char)
{
    int        i, j;
    int        leng;
    wchar_t    c;

    leng = wcslen(str_wchar);
    for (i=j=0; i<leng; i++, j++)
    {
        c = str_wchar[i];
        if (c == 0) {
            str_char[j] = '/0';
            break;
        }
        else if (c < 0x80) {
            str_char[j] = (char)str_wchar[i];
        }
        else {
            // Currently the non-alphanumeric characters are not supported.
            i++;
        }
    }

    str_char[j] = '/0';
}

 

 

 

 

 

 

原创粉丝点击