a2w_w2a

/********************************************************************
 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; }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值