You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.5 KiB
C++

#include <stdafx.h>
#include <Windows.h>
bool AsciiToUnicodeChar(const char * str, wchar_t * buffer, int lenOfBuffer)
{
if (lenOfBuffer < 4)
return false;
int len = lenOfBuffer - 2;
DWORD num = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0); //num为宽字符的个数
if ((DWORD)len < num)
num = len;
buffer[num] = L'\0';
//memset(buffer, 0, sizeof(wchar_t)*(num + 1));
MultiByteToWideChar(CP_ACP, 0, str, (int)strlen(str), buffer, num);
return true;
}
//调用者释放返回字符串的内存
wchar_t * AsciiToUnicodeChar(const char * str)
{
DWORD num = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0); //num为宽字符的个数
wchar_t * buffer = new wchar_t[num + 1];
memset(buffer, 0, sizeof(wchar_t)*(num + 1));
MultiByteToWideChar(CP_ACP, 0, str, (int)strlen(str), buffer, num);
return buffer;
}
//TODO:改成返回bool
char* UnicodeToAscii(const wchar_t * str, char * buffer, int lenOfBuffer)
{
if (lenOfBuffer <= 0 || buffer == 0 || str == 0)
return 0;
memset(buffer, 0, lenOfBuffer);
lenOfBuffer--;
DWORD num = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, 0);
if (num >= (DWORD)lenOfBuffer)
return NULL;
WideCharToMultiByte(CP_ACP, 0, str, -1, buffer, num, NULL, NULL);
return buffer;
}
//调用者负责释放返回的内存
char* UnicodeToAscii(const wchar_t * str)
{
DWORD num = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, 0);
char * buffer = new char[num + 1];
memset(buffer, 0, sizeof(char)*(num + 1));
WideCharToMultiByte(CP_ACP, 0, str, -1, buffer, num, NULL, NULL);
return buffer;
}