C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了将向量转换为char ** C大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个向量< std :: String>变量.我需要将它传递给接受char **作为输入参数的方法.

怎么办?如果可能,我需要通过一个可写的.

更新1:
在创建服务方法的工具中,我给参数作为std :: vector,但它会自动将限定符设置为&,这意味着我的方法定义将由以下工具生成

std::string SvcImpl::mymethodname ( const std::string par1,const std::vector<     std::string >& par2,const std::vector< std::string >& par3 )
{

}

自动调用方法,通过传递的参数中的值.
现在从这个方法里面我将在lib文件夹中的一个dll中调用一个方法,如下所示:

int method_to_be_called(char* par1,char ** par2,char ** par3,void* pRetvalue);

对于par1 – >我正在传递(char *)par1.c_str()

我需要知道如何传递par2和par3以及pRetValue的变量.
par2和par3的值在向量中可用,但最后一个参数pRetValue是一个输出参数,我需要将其作为std :: String返回.

对不起,如果我很混乱或提出非常基本的问题.

解决方法

只要函数修改char **中的传递,就可以解决问题,而不会复制所有的std :: String.否则,我可以看到没有任何选择,只能将所有内容复制到一个新的char **`结构(见第二个例子).
void old_func(char** carray,size_t sizE)
{
    for(size_t i = 0; i < size; ++i)
        std::cout << carraY[i] << '\n';
}

int main()
{
    std::vector<std::string> Strings { "one","two","three"};
    std::vector<char*> cStrings;

    for(size_t i = 0; i < Strings.size(); ++i)
        cStrings.push_BACk(const_cast<char*>(Strings[i].c_str()));

    // Do not change any of the Strings here as that will
    // invalidate the new data structure that relies on
    // the returned values from `c_str()`
    //
    // This is not an issue after C++11

    if(!cStrings.empty())
        old_func(&cStrings[0],cStrings.size());
}

示例2:如果函数必须修改传入的数据:

void old_func(char** carray,"three"};
    char** cStrings = new char*[Strings.size()];

    for(size_t i = 0; i < Strings.size(); ++i)
    {
        cStrings[i] = new char[Strings[i].size() + 1];
        std::strcpy(cStrings[i],Strings[i].c_str());
    }

    // Now the function can do what it likes (within the bounds)
    // with the passed in structure

    old_func(cStrings,Strings.size());

    // clean up memory

    for(size_t i = 0; i < Strings.size(); ++i)
        delete[] cStrings[i];

    delete[] cStrings;
}

EDIT5:解决一个更简单的解决方案,用于Post C 98代码(Thnx to Beyelerstudios)添加一个解决方案,允许该功能修改传入的数据.

大佬总结

以上是大佬教程为你收集整理的将向量转换为char ** C全部内容,希望文章能够帮你解决将向量转换为char ** C所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。