inv*_*ate 9 c++ python string swig vector
我想用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;
}
Run Code Online (Sandbox Code Playgroud)
我想将它包装成一个名为`mymod'的模块中的Python函数:
/*mymod.i*/
%module mymod
%include "typemaps.i"
%include "std_string.i"
%include "std_vector.i"
%{
#include "mymod.hpp"
%}
%include "mymod.hpp"
Run Code Online (Sandbox Code Playgroud)
当我用这个扩展构建时
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++']),
],
)
Run Code Online (Sandbox Code Playgroud)
然后导入它并尝试运行它,我收到此错误:
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 > >'
>>>
Run Code Online (Sandbox Code Playgroud)
我猜这是说SWIG不提供默认的类型映射,用于在Python字符串的Python列表和STL字符串的C++ STL向量之间进行转换.我觉得这是他们默认提供的东西,但也许我不知道要包含的正确文件.那我怎么能让它运作起来呢?
提前致谢!
Dem*_*hun 17
你需要告诉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"
Run Code Online (Sandbox Code Playgroud)
SWIG 确实支持将列表传递给以向量作为值或 const 向量引用的函数。http://www.swig.org/Doc2.0/Library.html#Library_std_vector的示例显示了这一点,我看不出您发布的内容有任何问题。还有一些事情是错误的;python 找到的 DLL 不是最新的,标头中的 using namespace std 混淆了执行类型检查的 SWIG 包装器代码(请注意,.hpp 中的“using namespace”语句通常是禁忌,因为它会提取所有内容从 std 到全局命名空间)等