函数原型需要 wchar_t* 输入参数,而手边只有wstring类型,怎么转换?
void Process(const unsigned char* pSrcChars, int srcSize, wchar_t* pDestChars, int* destSize)
{
}
int _tmain(int argc, _TCHAR* argv[])
{
std::wstring dest;
const std::string src;
int destSize = 0;
int srcSize = (int) src.length();
wchar_t dummy;
// compute size
Process((const unsigned char*) src.c_str(), srcSize, &dummy, &destSize);
//option 1-bad
dest.resize(destSize);
Process((const unsigned char*) src.c_str(), srcSize, (wchar_t*)dest.c_str(), &destSize);
//option 2-also bad
dest.resize(destSize);
Process((const unsigned char*) src.c_str(), srcSize, const_cast<wchar_t*>(dest.c_str()), &destSize);
//option 3-good
wchar_t* destChars = new wchar_t[destSize+1];
destChars[destSize] = L'\0';
Process((const unsigned char*) src.c_str(), srcSize, destChars, &destSize);
dest = std::wstring(destChars);
delete destChars;
return 0;
}
三种方法都可以编译通过。
[option 1]
dest.c_str() 得到C风格的以null结尾的字符串形式,以const修饰。(wchar_t*)dest.c_str() 强制去掉const。首先(casted type)variable 是C风格的转换,在cpp源文件中最好使用C++风格的转换,即specific_cast<casted type>(variable),specific_cast就是static_cast, const_cast, reinterpret_cast等。
用g++编译,打开-Wcast-qual 开关,会有warning。
$g++ -Wcast-qual test.cpp
warning: cast from type 'const wchar_t*' to type 'wchar_t*' casts away qualifiers
-Wcast-align
char *
is cast to an
int *
on machines where integers can only be accessed at two- or four-byte boundaries.
[option 2]
使用了C++风格的转换,用const_cast去掉了const属性。
option 1 和 option 2 都是不好的编码风格。尽量不要用。
[option 3]
推荐使用。先分配wchar_t*,使用,复制给wstring,清理动态分配内存。