【问题标题】:How to convert from LPWSTR** to std::vector<std::wstring>如何从 LPWSTR** 转换为 std::vector<std::wstring>
【发布时间】:2018-04-10 13:55:53
【问题描述】:

我有一个与 std::vector 一起使用的函数, 声明如下:

void MyFunc(std::vector<std::wstring> &vFillArray){
//....
//fill the vector with wstrings
//....
}

现在我想将我的函数导出到一个 DLL 库中并制作它 可用于 vb 6 应用程序。 按原样使用该库会使 vb 6 应用程序崩溃。 我必须将声明更改为 LPWSTR** (或我认为的 wchar_t**),但现在, 如何在我的 C++ 函数内部重新转换这种类型? 在内部,我使用 std::vector 用字符串填充向量。 有什么建议吗?

【问题讨论】:

  • 您确定 LPWSTR 吗?上次我写了一个供VB使用的DLL,我不得不使用BSTR。
  • LPWSTR 是(在 Windows 下)wchar_t *,所以 LPWSTR * 将是 wchar_t **。要求与LPWSTR ** 进行转换是没有意义的,因为类型不兼容,除非您还指定为什么您正在调用的函数在其参数类型中有一个额外的*。如果您确实需要 LPWSTR *,我会提供提示 - std::vector 和 std::wstring 元素都是连续的(保证 C++11 及更高版本,在 C++11 之前不保证,但通常是这种情况)但两者都是还为其元素动态分配内存,因此vector&lt;wstring&gt; 中的wchar_ts 不连续。
  • 跨进程内存(DLL 也是)中的每种分配技术都很困难/被禁止。你可以使用微软的 COM API,但是很难
  • @KarstenKoop 不,我不确定。我敢肯定,对于正常的 wstring,我必须使用 LPWSTR 和 vb 6 停止崩溃:之前 -> std::wstring after -> LPWSTR 我认为可以按预期工作(但我是 C++ 的初学者,我不确定) 对于 std::vector<:wstring> 我需要使用 LPWSTR** 或 WCHAR_T** 我可以稍后测试是否必须使用 * 或 **。现在我想知道如何在内部将其从 LPWSTR 数据类型重新转换为 std::vector<:wstring>
  • @Peter 我需要使用一些与 vb 6 兼容的数据类型(我认为 LPWSTR** 是我需要的)。然后我需要将其转换为 std::vector<:wstring> 因为我在 c++ 中的函数使用 wstring 的向量

标签: c++ vector wstring lpwstr


【解决方案1】:

假设LPWSTR与wchar_t相同,则可以使用std::vector的常用迭代器赋值构造函数和函数:

wchar_t const *raw_data[] = {L"Hello", L"World", L"Test"};
std::vector<std::wstring> vec(raw_data, raw_data+2); // construct with first 2 elements
std::wcout << vec[0] << ' ' << vec[1] << '\n';
wchar_t const ** raw_ptr = raw_data;
vec.assign(raw_ptr, raw_ptr+3); // assing 3 elements
std::wcout << vec[0] << ' ' << vec[1] << ' ' << vec[2] << '\n';

【讨论】:

    猜你喜欢
    • 2016-08-17
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多