如何转换向量<wstring>到 wchar_t**? [英] How to convert a vector<wstring> to a wchar_t**?

查看:35
本文介绍了如何转换向量<wstring>到 wchar_t**?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个与 C 兼容的(友好的)返回类型,以便我的 C++ 函数可以与基于 C 的函数一起使用.

I need to create a C compatible (friendly) return type so that my C++ functions can be used to work with C-based functions.

如何将 wstring 向量转换为 wchar_t** 数组?

How I can convert a vector of wstring to a wchar_t** array?

推荐答案

这是将 std::wstring 的向量转换为基于 wchar_t** 的函数细绳.由于使用了 DisposeBuffer(),它也不会泄漏任何内存;呼叫不同于其他答案.

This is the function for converting a vector of std::wstring to a wchar_t** based string. It also won't leak any memory because of using that DisposeBuffer(); call unlike other answers.

wchar_t ** xGramManipulator::GetCConvertedString(vector< wstring> const &input)
{
    DisposeBuffer();  //This is to avoid memory leak for calling this function multiple times
    cStringArraybuffer = new wchar_t*[input.size()]; //cStringArraybuffer is a member variable of type wchar_t**
    for (int i = 0; i < input.size(); i++)
    {
        cStringArraybuffer[i] = new wchar_t[input[i].size()+1];
        wcscpy_s(cStringArraybuffer[i], input[i].size() + 1, input[i].c_str());
        cStringArraySize++;
    }
    return cStringArraybuffer;
}

这是避免内存泄漏的 DisposeBuffer 辅助函数:

And this is the DisposeBuffer Helper Function to avoid memory leaks:

void xGramManipulator::DisposeBuffer(void)
{
    for (size_t i = 0; i < cStringArraySize; i++)
    {
        delete [] cStringArraybuffer[i];
    }
    delete [] cStringArraybuffer;
    cStringArraybuffer = nullptr;
    cStringArraySize = 0;
}

在这些之前在你的构造函数中分配一个虚拟空间:

And prior to these allocate a dummy space in your constructor:

xGramManipulator::xGramManipulator()
{
    //allocating dummy array so that when we try to de-allocate it in GetCConvertedString(), dont encounter any undefined behavior

    cStringArraybuffer = new wchar_t*[1];
    cStringArraySize = 0;
    for (int i = 0; i < 1; i++)
    {
        cStringArraybuffer[i] = new wchar_t[1 + 1];
        cStringArraySize++;
    }
}

一切都完成了.

这篇关于如何转换向量&lt;wstring&gt;到 wchar_t**?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆