描述:
我在编写一个COM组件,组件内的方法原型如下:
STDMETHODIMP CFileTrans::UploadFile(BSTR FileIdentifier,int *result);
我想使用char数组作为文件名打开一个文件,使用TCP流套接字实施文件传输。请问:怎样将BSTR字符串转换为char数组?
解决方案1:
CComBSTR、_bstr_t是对BSTR的封装,BSTR是指向字符串的32位指针。
char *转换到BSTR可以这样: BSTR b=_com_util::ConvertStringToBSTR("数据");///使用前需要加上头文件comutil.h
反之可以使用char *p=_com_util::ConvertBSTRToString(b);
STDMETHODIMP CFileTrans::UploadFile(BSTR FileIdentifier,int *result);
char cFileId[MAX_LEN];
wcstombs(cFileId, FileIdentifier, sizeof(cFileId))
下面是最安全的!为了你的项目没有漏洞!
//------------------------//
// Convert char * to BSTR //转换后的BSTR用完后通过::SysFreeString();删除
//------------------------//
inline BSTR ConvertStringToBSTR(const char* pSrc)
{
if(!pSrc) return NULL;
DWORD cwch;
BSTR wsOut(NULL);
if(cwch = ::MultiByteToWideChar(CP_ACP, 0, pSrc,
-1, NULL, 0))//get size minus NULL terminator
{
cwch--;
wsOut = ::SysAllocStringLen(NULL, cwch);
if(wsOut)
{
if(!::MultiByteToWideChar(CP_ACP,
0, pSrc, -1, wsOut, cwch))
{
if(ERROR_INSUFFICIENT_BUFFER == ::GetLastError())
return wsOut;
::SysFreeString(wsOut);//must clean up
wsOut = NULL;
}
}
};
return wsOut;
};
//------------------------//
// Convert BSTR to char * //转换后的char*用完后通过delete []删除
//------------------------//
inline char* ConvertBSTRToString(BSTR pSrc)
{
if(!pSrc) return NULL;
//convert even embeded NULL
DWORD cb,cwch = ::SysStringLen(pSrc);
char *szOut = NULL;
if(cb = ::WideCharToMultiByte(CP_ACP, 0,
pSrc, cwch + 1, NULL, 0, 0, 0))
{
szOut = new char[cb];
if(szOut)
{
szOut[cb - 1] = '\0';
if(!::WideCharToMultiByte(CP_ACP, 0,
pSrc, cwch + 1, szOut, cb, 0, 0))
{
delete []szOut;//clean up if failed;
szOut = NULL;
}
}
}
return szOut;
};
inline HRESULT BstrToString( const BSTR pString, char *pBuf, DWORD dwBufSize )
{
if ( NULL == pString )
{
return S_FALSE;
}
UINT nLen = SysStringLen( pString );
memset( pBuf, 0, dwBufSize );
if ( 0 == nLen )
{
return S_OK;
}
nLen *= sizeof( BSTR[1] );
if ( 0 == WideCharToMultiByte( CP_ACP, 0, pString,
nLen, pBuf, dwBufSize, NULL, NULL ) )
{
return S_FALSE;
}
return TRUE;
}
(3) BSTR转换成char*
方法一,使用ConvertBSTRToString。例如:
#include
#pragma comment(lib, "comsupp.lib")
int _tmain(int argc, _TCHAR* argv[]){
BSTR bstrText = ::SysAllocString(L"Test");
char* lpszText2 = _com_util::ConvertBSTRToString(bstrText);
SysFreeString(bstrText); // 用完释放
delete[] lpszText2;
return 0;
}