函数原型 int WideCharToMultiByte( UINT CodePage, //指定执行转换的代码页 DWORD dwFlags, //允许你进行额外的控制,它会影响使用了读音符号(比如重音)的字符 LPCWSTR lpWideCharStr, //指定要转换为宽字节字符串的缓冲区 int cchWideChar, //指定由参数lpWideCharStr指向的缓冲区的字符个数(注意:需要转换的字符串长度,为-1时,表示取到null的字符串) LPSTR lpMultiByteStr, //指向接收被转换字符串的缓冲区 int cchMultiByte, //指定由参数lpMultiByteStr指向的缓冲区最大值 LPCSTR lpDefaultChar, //遇到一个不能转换的宽字符,函数便会使用pDefaultChar参数指向的字符 LPBOOL pfUsedDefaultChar//至少有一个字符不能转换为其多字节形式,函数就会把这个变量设为TRUE );
示例:
#include <Windows.h>
#include <stdio.h>
#define MAX_BUFFER_SIZE 256
char * W2C(const wchar_t *wstr, int n)
{
static char sBuffer[MAX_BUFFER_SIZE];
memset(sBuffer, 0, MAX_BUFFER_SIZE);
if (n > MAX_BUFFER_SIZE) n = MAX_BUFFER_SIZE;
int i = WideCharToMultiByte(CP_ACP, 0, wstr, n, sBuffer, MAX_BUFFER_SIZE, NULL, NULL);
return sBuffer;
}
void main( void )
{
char *sRes;
wchar_t wsName[] = L"中文测试0123456789~1-";
sRes = W2C(wsName, wcslen(wsName));
printf("%s, %d\n", sRes, strlen(sRes));
}