我想用SWIG包装一个C++函数,该函数接受STL字符串 vector 作为输入参数:
#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;
}
我想将其包装到名为mymod的模块中的Python函数中:
/*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字符串列表和STL字符串的C++ STL vector 之间进行转换的默认类型映射。我觉得这是他们默认情况下可能会提供的东西,但是也许我不知道要包含的文件正确。那么我怎样才能使它正常工作呢?
提前致谢!
最佳答案
您需要告诉SWIG您想要 vector 字符串类型映射。它不能神奇地猜测所有可能存在的所有不同 vector 类型。
这是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"