#include <iostream>
#include <windows.h>
#include <tchar.h>
#include <memory>
using namespace std;
std::shared_ptr<char> wchar2char(const wchar_t* wchar)
{
char * pchar;
int len = WideCharToMultiByte(CP_ACP, 0, wchar, wcslen(wchar), NULL, 0, NULL, NULL);
pchar = new char[len + 1];
WideCharToMultiByte(CP_ACP, 0, wchar, wcslen(wchar), pchar, len, NULL, NULL);
pchar[len] = '\0';
return std::shared_ptr<char>(pchar);
}
std::shared_ptr<wchar_t> char2wchar(const char* cchar)
{
wchar_t *pwchar;
int len = MultiByteToWideChar(CP_ACP, 0, cchar, strlen(cchar), NULL, 0);
pwchar = new wchar_t[len + 1];
MultiByteToWideChar(CP_ACP, 0, cchar, strlen(cchar), pwchar, len);
pwchar[len] = '\0';
return std::shared_ptr<wchar_t>(pwchar);
}
int main(int argc, char* argv[])
{
wchar_t* wc = L"I LOVE 中国!";
std::shared_ptr<char> spc = wchar2char(wc);
cout << spc << endl;
std::shared_ptr<wchar_t> spwc = char2wchar(spc.get());
std::shared_ptr<char> spc2 = wchar2char(spwc.get());
cout << spc2 << endl;
system("pause");
return 0;
}
结果: