/********************************************************************
file name : const2buffer.h
author : Clark
created : 1:8:2011
purpose :
*********************************************************************/
#pragma once
#include <tchar.h>
#include <windows.h>
class const2buffer
{
public:
static const2buffer make_c2b(const TCHAR* pConst) throw(const TCHAR*)
{
try{ return (const2buffer(pConst)); }
catch(const TCHAR* pError){ throw pError; }
}
explicit const2buffer(const TCHAR* pConst) throw(const TCHAR*):m_pBuf(NULL)
{
if( NULL != pConst)
{
int iLen = _tcslen(pConst);
try{ m_pBuf = new TCHAR[iLen+1]; }
catch(std::bad_alloc)
{
m_pBuf = NULL;
TCHAR _tcsError[256];
_stprintf(_tcsError,_T("Failed in const2buffer -> const2buffer -> new TCHAR[%d]\n"),iLen);
throw _tcsError;
}
_tcscpy(m_pBuf,pConst);
m_pBuf[iLen] = '\0';
}
}
~const2buffer()
{
if( NULL != m_pBuf)
{
delete[] m_pBuf;
m_pBuf = NULL;
}
}
operator TCHAR*()
{
return m_pBuf;
}
private:
TCHAR* m_pBuf;
};
class a2w
{
wchar_t* buffer;
public:
explicit a2w():buffer(0){}
explicit a2w(const char* str) throw(const TCHAR*):buffer(0)
{
try { init(str); }
catch(const TCHAR* pError){ throw pError; }
}
void init(const char* str) throw(const TCHAR*)
{
if( NULL != buffer)
delete[] buffer;
if(NULL != str)
{
int nLen = ::MultiByteToWideChar(CP_ACP,0,str,-1,NULL,0);
try{ buffer = new wchar_t[nLen+1];}
catch(std::bad_alloc)
{
buffer = NULL;
TCHAR _tcsError[256];
_stprintf(_tcsError,_T("Failed in a2w -> init -> new wchar_t[%d]\n"),nLen+1);
throw _tcsError;
}
memset(buffer,0,(nLen+1)*sizeof(wchar_t));
::MultiByteToWideChar(CP_ACP,0,str,-1,buffer,nLen);
buffer[nLen] = 0;
}
}
~a2w()
{
delete[] buffer;
}
operator const wchar_t*() { return buffer; }
};
class w2a
{
char *buffer;
public:
explicit w2a():buffer(0){}
explicit w2a(const wchar_t* str) throw(const TCHAR*):buffer(0)
{
try { init(str); }
catch(const TCHAR* pError){ throw pError; }
}
void init(const wchar_t* str) throw(const TCHAR*)
{
if( NULL != buffer)
delete[] buffer;
if(NULL != str)
{
int nLen = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
try{ buffer = new char[nLen+1]; }
catch(std::bad_alloc)
{
buffer = NULL;
TCHAR _tcsError[256];
_stprintf(_tcsError,_T("Failed in w2a -> init -> new char[%d]\n"),nLen+1);
throw _tcsError;
}
memset(buffer,0,(nLen+1)*sizeof(char));
::WideCharToMultiByte (CP_ACP, 0,str, -1,buffer , nLen, NULL,NULL);
buffer[nLen] = 0;
}
}
~w2a() { delete[] buffer; }
operator const char*() { return buffer; }
};