首页 > 解决方案 > 复制宽字符串

问题描述

我正在尝试创建一个应用程序,其中我有一个尝试复制宽字符串的函数。我目前正在使用_wcsdup(),因为它是一个 Windows 应用程序,对我来说一切正常。但是我需要创建一个多平台功能,所以_wcsdup()(这是一个 Windows 功能)对我来说不起作用。

现在,我的代码看起来像这样:

wchar_t* out = _wcsdup(wstring.str().c_str());

wstring字符串流在哪里。

现在,我正在寻找适用于 Windows 和 Linux 的通用功能,以使该功能正常工作。

标签: c++linuxwindowswidecharwchar

解决方案


标准的跨平台等效项是使用/分配/释放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 风格函数时。


推荐阅读