在代码中创建argc argv [英] create argc argv in the code

查看:88
本文介绍了在代码中创建argc argv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您很新手的问题,但我想不通:

Hi very newbie question but I just can't figure it out:

我有一个名为bar的函数

I have a function named bar

class foo
{
    public:
        bool bar(int argc, char** argv);
}

argv应该包含

"--dir" and "/some_path/"

如何创建argv和argc以便将它们传递给bar()?我已经尝试了很多方法,但是我无法正确获得指针和类型转换.

How do I create argv and argc so that I can pass them into bar() ? I've tried many ways but I just can't get pointer and type conversion right.

因此,我不想从命令行获取argv,而是要在代码中创建它.

So instead of getting argv from command line, I want to create it in the code.

谢谢您的输入!

推荐答案

我最喜欢的方式是这样的:

My favourite way is like this:

std::vector<std::string> arguments = {"--dir", "/some_path"};

std::vector<char*> argv;
for (const auto& arg : arguments)
    argv.push_back((char*)arg.data());
argv.push_back(nullptr);

f.bar(argv.size() - 1, argv.data());

请注意,如果参数是静态的且未更改,那么这有点过头了.但是这种方法具有符合RAII的优势.它为您管理内存并在适当的时候删除对象.因此,如果参数列表是动态的,那么这是最干净的方法.

Note, that if arguments are static and do not change, then this is a little bit overkill. But this approach has advantage of being RAII compliant. It manages memory for you and deletes objects at right moment. So if argument list is dynamic, then it is the cleanest way.

除此之外,如果 f.bar 修改argv数组中的数据,则此代码从技术上讲就是UB.通常情况并非如此.

Beside that, this code technically is UB if f.bar modifies data in argv array. Usually this is not the case.

这篇关于在代码中创建argc argv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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