char和wchar_t互转的操作类


//@file widechar.h
//@author norkts<[email protected]>

class WideChar{
public:
	WideChar();
	WideChar(const wchar_t* in);
	WideChar(const char* in);
	~WideChar();

	char* toChar(){
		return data;
	}

	wchar_t* toWchar(){
		return wdata;
	}

	int size(){
		return _size;
	}

	int wsize(){
		return _wsize;
	}

	void operator=(const wchar_t* in){
		delete[] wdata;
		delete[] data;

		assign(in);
	}

	void operator=(const char* in){
		delete[] wdata;
		delete[] data;

		assign(in);
	}

private:
	void assign(const wchar_t* in);
	void assign(const char* in);
private:
	wchar_t* wdata;
	char* data;
	int _wsize = 0;
	int _size = 0;
};



//@file widechar.cpp
//@author norkts<[email protected]>

#include "WideChar.h"
WideChar::WideChar(){

}

WideChar::WideChar(const wchar_t* in){
	assign(in);
}

WideChar::WideChar(const char* in){
	assign(in);
}

WideChar::~WideChar(){
	delete[] data;
	delete[] wdata;
}

void WideChar::assign(const wchar_t* in){
	_wsize = wcslen(in);

	wdata = new wchar_t[_wsize + 1];
	wmemset(wdata, 0, _wsize + 1);
	wmemcpy(wdata, in, _wsize);

	_size = _wsize * 2;
	data = new char[_size + 1];
	memset(data, 0, _size + 1);

	WideCharToMultiByte(CP_ACP, 0, wdata, -1, data, _size, NULL, NULL);

	_size = strlen(data);
}

void WideChar::assign(const char* in){
	_size = strlen(in);
	data = new char[_size + 1];
	memset(data, 0, _size + 1);
	memcpy(data, in, _size);

	_wsize = _size * 2;

	wdata = new wchar_t[_wsize + 1];
	wmemset(wdata, 0, _wsize + 1);

	MultiByteToWideChar(CP_ACP, 0, data, -1, wdata, _size);

	_wsize = wcslen(wdata);
}

你可能感兴趣的:(C++)