【发布时间】:2010-12-25 01:21:01
【问题描述】:
我有这段 C 风格的初始化代码:
const char * const vlc_args[] =
{
"-I", "dummy",
"--ignore-config",
"--extraintf=logger",
"--verbose=2"
"--plugin-path=/usr/lib/vlc"
};
//tricky calculation of the char space used
libvlc_new(sizeof(vlc_args)/sizeof(vlc_args[0]), vlc_args, &exc);
由于我需要使--plugin-path 参数动态化,我不能再使用静态数组。所以我想出了一个 C++ 替代方案:
std::string pluginpath = "test";
libvlc_exception_t exc;
std::vector<std::string> args;
args.push_back("-I");
args.push_back("dummy");
args.push_back("--ignore-config");
args.push_back("--extraintf=logger");
args.push_back("--verbose=2");
args.push_back("--ipv4");
args.push_back("--plugin-path=" + pluginpath);
std::string combinedString;
for (size_t idx = 0; idx < args.size(); ++idx)
{
combinedString.append(args[idx]);
combinedString.resize(combinedString.size() + 1);
combinedString[combinedString.size() - 1] = 0;
}
combinedString.resize(combinedString.size() + 1);
combinedString[combinedString.size() - 1] = 0;
size_t size = combinedString.size();
const char * data = combinedString.c_str();
libvlc_new(size, &data, &exc); // => error occurs here (not at end of scope or anything)
但这会导致分段错误。所以我的代码中一定有一个错误,我似乎找不到..有人能发现吗?
解决了!
感谢 Joseph Grahn 和 Jason Orendorff。我对 C 样式数组的内存布局的想法是错误的。我认为所有数据都组织成一个大的顺序块。实际上,它是指向每个单独字符串的第一个字符的指针列表。
此代码有效:
std::vector<const char*> charArgs;
for (size_t idx = 0; idx < args.size(); ++idx)
{
charArgs.push_back(&(args[idx][0]));
}
mVLCInstance = libvlc_new(charArgs.size(),
&charArgs[0],
&mVLCException);
【问题讨论】:
-
在调试器中运行它并告诉我们它出现在哪一行。
-
它在没有调试符号的情况下在目标代码中出现段错误。在我的代码中,这发生在 libvlc_new 调用期间。
-
为什么要将 &data 传递给 libvlc_new 函数?在原始代码中,第二个参数是 const char * 类型,现在您传递的是 const char **。从第二个参数中删除“&”。
标签: c++