gpt4 book ai didi

python - 我怎样才能从 python 得到一个 char*[]

转载 作者:太空宇宙 更新时间:2023-11-04 11:31:42 26 4
gpt4 key购买 nike

我使用 swig 包装了一些 C++ api 函数。有一个函数,接口(interface)是f(char*[] strs)。

如何将有效参数传递给此函数。这就是我所做的。

str = ["str","str2"]
f(str)

会报错

TypeError: in method 'f', argument 1 of type 'char *[]  

最佳答案

SWIG 不会自动将数组转换为 Python 列表。由于您使用的是 C++,请为您的 f 使用 std::string 和 std::vector,然后 SWIG 将自动进行所有必要的转换(不要忘记包含“std_vector.i”等,请参阅 SWIG 文档):

void f(std::vector<std::string> > strs)

如果你不能修改f的声明,你可以在.i中创建一个%inline包装器:

%inline {
void f(const std::vector<std::string> >& strs)
{
// create tmpCharArray of type char*[] from strs
const char* tmpCharArray[] = new const char* [strs.size()];
for (i=0; i<strs.size(); i++)
tmpCharArray[i] = strs[i].c_str();
f(tmpCharArray);
delete[] tmpCharArray;
}
}

关于python - 我怎样才能从 python 得到一个 char*[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24524011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com