我想用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你想要一个向量字符串类型映射。它不会神奇地猜测所有可能存在的不同向量类型。
这是Scholli提供的链接:
SWIG确实支持将列表传递给以向量为值的函数或常量向量引用。在http://www.swig.org/Doc2.0/Library.html#Library_std_vector上的例子显示了这一点,我看不出你发布的内容有什么问题。有其他问题;python找到的DLL不是最新的,头中的using namespace std混淆了执行类型检查的SWIG包装器代码(注意,.hpp中的“using namespace”语句通常是一个no no,因为它将std中的所有内容都拉入全局命名空间)等等
相关问题 更多 >
编程相关推荐