SWIG包装c++ for Python:将字符串列表转换为STL字符串的STL向量

SWIG wrapping C++ for Python: translating a list of strings to an STL vector of STL strings

本文关键字:字符串 STL 列表 转换 向量 c++ 包装 for Python SWIG      更新时间:2023-10-16

我想用SWIG包装一个c++函数,它接受STL字符串向量作为输入参数:

#include <iostream>
#include <string>
#include <vector>
using namespace std;
void print_function(vector<string> strs) {
  for (unsigned int i=0; i < strs.size(); i++)
  cout << strs[i] << endl;
}

我想把它包装成一个Python函数,这个函数可以在一个名为' mymod'的模块中使用:

/*mymod.i*/
%module mymod
%include "typemaps.i"
%include "std_string.i"
%include "std_vector.i"
%{
 #include "mymod.hpp"
%}
%include "mymod.hpp"

当我用

构建这个扩展时
from distutils.core import setup, Extension
setup(name='mymod',
  version='0.1.0',
  description='test module',
  author='Craig',
  author_email='balh.org',
  packages=['mymod'],
  ext_modules=[Extension('mymod._mymod',
                         ['mymod/mymod.i'],
                         language='c++',
                         swig_opts=['-c++']),
                         ],
  )

然后导入并尝试运行它,我得到这个错误:

Python 2.7.2 (default, Sep 19 2011, 11:18:13) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymod
>>> mymod.print_function("hello is seymour butts available".split())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: in method 'print_function', argument 1 of type 'std::vector<  std::string,std::allocator< std::string > >'
>>> 

我猜这是说SWIG没有提供默认的类型映射,用于在Python字符串的Python列表和STL字符串的c++ STL向量之间进行转换。我觉得这是他们在默认情况下提供的东西,但可能我不知道应该包含哪个文件。那么我怎样才能让它工作呢?

提前感谢!

您需要告诉SWIG您想要一个向量字符串类型映射。它不会神奇地猜测所有可能存在的不同向量类型。

这是在Schollii提供的链接:

//To wrap with SWIG, you might write the following:
%module example
%{
#include "example.h"
%}
%include "std_vector.i"
%include "std_string.i"
// Instantiate templates used by example
namespace std {
   %template(IntVector) vector<int>;
   %template(DoubleVector) vector<double>;
   %template(StringVector) vector<string>;
   %template(ConstCharVector) vector<const char*>;
}
// Include the header file with above prototypes
%include "example.h"

SWIG支持将列表传递给接受vector作为值的函数或const vector引用。http://www.swig.org/Doc2.0/Library.html#Library_std_vector的例子显示了这一点,我看不出你发布的内容有什么问题。还有别的地方出了问题;python发现的DLL不是最新的,头文件中的using命名空间std会混淆进行类型检查的SWIG包装器代码(请注意,.hpp中的"using namespace"语句通常是禁止的,因为它将所有内容从std拉到全局命名空间中),等等。