Aut*_*tAM 48 c++ unicode winapi mingw type-conversion
我试过实现这样的函数,但不幸的是它不起作用:
const wchar_t *GetWC(const char *c)
{
const size_t cSize = strlen(c)+1;
wchar_t wc[cSize];
mbstowcs (wc, c, cSize);
return wc;
}
Run Code Online (Sandbox Code Playgroud)
我的主要目标是能够在Unicode应用程序中集成普通的char字符串.我们非常感谢您提供的任何建议.
And*_*erd 37
在您的示例中,wc
是一个局部变量,在函数调用结束时将被释放.这会使您进入未定义的行为领域.
简单的解决方法是:
const wchar_t *GetWC(const char *c)
{
const size_t cSize = strlen(c)+1;
wchar_t* wc = new wchar_t[cSize];
mbstowcs (wc, c, cSize);
return wc;
}
Run Code Online (Sandbox Code Playgroud)
请注意,调用代码必须释放此内存,否则将导致内存泄漏.
Che*_*Alf 31
使用std::wstring
而不是C99可变长度数组.当前标准保证了连续的缓冲区std::basic_string
.例如,
std::wstring wc( cSize, L'#' );
mbstowcs( &wc[0], c, cSize );
Run Code Online (Sandbox Code Playgroud)
C++不支持C99可变长度数组,因此如果您将代码编译为纯C++,它甚至不会编译.
通过该更改,您的函数返回类型也应该是std::wstring
.
请记住在中设置相关的区域设置main
.
例如,setlocale( LC_ALL, "" )
.
干杯&hth.,
const char* text_char = "example of mbstowcs";
size_t length = strlen(text_char );
Run Code Online (Sandbox Code Playgroud)
用法示例“mbstowcs”
std::wstring text_wchar(length, L'#');
//#pragma warning (disable : 4996)
// Or add to the preprocessor: _CRT_SECURE_NO_WARNINGS
mbstowcs(&text_wchar[0], text_char , length);
Run Code Online (Sandbox Code Playgroud)
用法示例“mbstowcs_s”
Microsoft 建议使用“mbstowcs_s”而不是“mbstowcs”。
链接:
wchar_t text_wchar[30];
mbstowcs_s(&length, text_wchar, text_char, length);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
155054 次 |
最近记录: |