我必须调用一个接受字符串指针数组的c函数。实施例
void cFunction(char* cities[], int count)
{
for(int i = 0; i < count; ++i )
{
printf("%s\n", cities[i]);
}
}
假设该功能属于某些第三方的libabry;它无法改变 我可以声明一个静态数组并像这样调用函数
char* placesA[] = {"Teakettle Junction", "Assawoman Bay", "Land O' Lakes", "Ion", "Rabbit Hask" };
cFunction(placesA, 5);
这样可行。但是我的数据是动态的,即数组的大小在运行时改变很多次
所以我尝试了这个
std::vector<std::string> placesB(placesA, placesA + 5);
cFunction(&placesB[0], 5); // this won't work because std::string != char*[]
试过这个
std::vector<char*> placesC;
cFunction(&placesC[0], 5);
我发现placesC
笨拙地同时填充以避免内存泄漏我正在寻找既有效的解决方案(尽可能少的字符串复制,最好使用STL和/或Boost)
答案 0 :(得分:3)
您可以在每个字符串上使用vector<char*>
编写一个从vector<string>
填充.c_str()
的函数。
答案 1 :(得分:1)
无论你如何切片,都会有一些尴尬。如果C API确实需要可修改的数组,那么这就是你需要提供的 - 你必须将你的字符串复制到。如果它不修改字符串,那么您可以使用std::vector
const char*
,其中字符串数据仍由基础std::string
对象拥有;你必须要小心,C API不会保留对这些字符串的引用,并在修改或取消分配字符串后尝试访问它们。
例如,这是一种方法:
// Unary functor which calls c_str() on a std::string object
struct StdStringCStrFunctor
{
const char *operator() (const std::string& str) { return str.c_str(); }
};
...
std::vector<std::string> places;
... // populate places
// Convert to array of C strings
std::vector<const char *> placesCStr(places.size());
std::transform(places.begin(), places.end(), placesCStr.begin(), StdStringCStrFunctor());
cFunction(const_cast<char**>(&placesCStr[0]), placesCStr.size());