我想将一个向量作为第二个参数传递给 execvp。是否可以?
问问题
7029 次
3 回答
8
是的,它可以通过利用向量使用的内部数组来非常干净地完成。
这将起作用,因为标准保证其元素是连续存储的(请参阅https://stackoverflow.com/a/2923290/383983)
#include <vector>
using namespace std;
int main(void) {
vector<char *> commandVector;
// do a push_back for the command, then each of the arguments
commandVector.push_back("echo");
commandVector.push_back("testing");
commandVector.push_back("1");
commandVector.push_back("2");
commandVector.push_back("3");
// push NULL to the end of the vector (execvp expects NULL as last element)
commandVector.push_back(NULL);
// pass the vector's internal array to execvp
char **command = &commandVector[0];
int status = execvp(command[0], command);
return 0;
}
于 2012-04-17T17:37:20.777 回答
3
是的,它可以通过利用向量使用的内部数组来非常干净地完成。
这将起作用,因为标准保证其元素是连续存储的(请参阅https://stackoverflow.com/a/2923290/383983)
#include <vector>
using std::vector;
int main() {
vector<char*> commandVector;
// do a push_back for the command, then each of the arguments
commandVector.push_back(const_cast<char*>("echo"));
commandVector.push_back(const_cast<char*>("testing"));
commandVector.push_back(const_cast<char*>("1"));
commandVector.push_back(const_cast<char*>("2"));
commandVector.push_back(const_cast<char*>("3"));
// push NULL to the end of the vector (execvp expects NULL as last element)
commandVector.push_back(NULL);
int status = execvp(command[0], &command[0]);
return 0;
}
执行 const_cast 以避免“从字符串常量到 'char*' 的不推荐转换”。字符串文字在 C++ 中实现为“const char*”。const_cast 是这里最安全的强制转换形式,因为它只删除了 const 而不会做任何其他有趣的事情。execvp 无论如何都不会编辑这些值。
如果您想避免所有强制转换,您必须通过将所有值复制到不值得的 'char*' 类型来使此代码复杂化。
于 2017-12-08T12:40:20.800 回答
2
不直接;您需要以某种方式将向量表示为以 NULL 结尾的字符串指针数组。如果它是一个字符串向量,那很简单;如果是其他类型的数据,您必须弄清楚如何将其编码为字符串。
于 2011-05-01T06:44:39.940 回答