如何从python中获取char * []

时间:2014-07-02 06:08:43

标签: python c++ swig

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

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

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

会抛出错误

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

1 个答案:

答案 0 :(得分:1)

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

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;
     }
}
相关问题