【发布时间】:2012-01-18 03:23:32
【问题描述】:
我想用 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 向量之间进行转换的默认类型映射。我觉得这是他们默认可能在某处提供的东西,但也许我不知道要包含的正确文件。那么我怎样才能让它工作呢?
提前致谢!
【问题讨论】:
标签: c++ python string vector swig