c++ - 复制宽字符串
问题描述
我正在尝试创建一个应用程序,其中我有一个尝试复制宽字符串的函数。我目前正在使用_wcsdup()
,因为它是一个 Windows 应用程序,对我来说一切正常。但是我需要创建一个多平台功能,所以_wcsdup()
(这是一个 Windows 功能)对我来说不起作用。
现在,我的代码看起来像这样:
wchar_t* out = _wcsdup(wstring.str().c_str());
wstring
字符串流在哪里。
现在,我正在寻找适用于 Windows 和 Linux 的通用功能,以使该功能正常工作。
解决方案
标准的跨平台等效项是使用/分配/释放wchar_t[]
缓冲区(或者,如果绝对需要,/以反映 的行为),使用或将字符从该缓冲区复制,例如:new[]
delete[]
malloc()
free()
_wcsdup()
std::copy()
std::memcpy()
wstring
std::wstring w = wstring.str();
wchar_t* out = new wchar_t[w.size()+1];
std::copy(w.begin(), w.end(), out);
w[w.size()] = L'\0';
...
delete[] out;
/*
std::wstring w = wstring.str();
wchar_t* out = (wchar_t*) malloc((w.size() + 1) * sizeof(wchar_t));
std::copy(w.begin(), w.end(), out);
w[w.size()] = L'\0';
...
free(out);
*/
std::wstring w = wstring.str();
size_t size = w.size() + 1;
wchar_t* out = new wchar_t[size];
std::memcpy(out, w.c_str(), size * sizeof(wchar_t));
...
delete[] out;
/*
std::wstring w = wstring.str();
size_t size = (w.size() + 1) * sizeof(wchar_t);
wchar_t* out = (wchar_t*) malloc(size);
std::memcpy(out, w.c_str(), size);
...
free(out);
*/
但是,无论哪种方式,既然str()
返回 astd::wstring
开始,你最好还是坚持使用std::wstring
而不是使用wchar_t*
:
std::wstring out = wstring.str();
您可以使用out.c_str()
或者out.data()
如果您需要 a (const) wchar_t*
,例如在传递out
给采用空终止字符串指针的 C 风格函数时。
推荐阅读
- jquery - 仅当 img src 存在时如何显示 div?
- binary - 更改为没有数组的二进制
- php - 如何修复 PHP 代码中未定义的变量?
- excel - 平面和点之间的二维角度分量
- node.js - 跟踪从 redux action 到 reducer 的时间
- javascript - 为javascript执行INT?
- php - Laravel 模型或 Laravel 的工作方式
- python - XlsxWriter 中的条形着色取决于正/负值
- c - 检查字符串是否为回文(CodeSignal 测试用例问题)
- bash - Jenkins Pipiline:让 awk 命令玩得好