wchar_t和char转换

时间:2021-12-14 20:12:46

char* W2C(const wchar_t *pwstr)
{
 int nlength = wcslen(pwstr);
 //获取转换后的长度 
 int nbytes = WideCharToMultiByte(0, 0, pwstr, nlength, NULL, 0, NULL, NULL);
 char* pcstr = new char[nbytes + 1];
 // 通过以上得到的结果,转换unicode 字符为ascii 字符 
 WideCharToMultiByte(0, 0, pwstr, nlength, pcstr, nbytes, NULL, NULL);
 pcstr[nbytes] = '\0';
 return pcstr;
}

bool C2W(const char* str, wchar_t* wstr)
{
 int len = MultiByteToWideChar(CP_OEMCP, 0, str, -1, wstr, 0);
 return len == MultiByteToWideChar(CP_OEMCP, 0, str, -1, wstr, len);
}

wchar_t name[10];
wcscpy(name, L"userdata");    将char赋值为 wchar_t

wchar_t *utf16_to_wchar(uint16_t *str, int len) {
 int i = 0;
 wchar_t *buf = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
 for (; i < len; i++)
  buf[i] = (wchar_t)str[i];
 buf[len] = L'\0';
 return buf;
}