SWIG包装c++ for Python:将字符串列表转换为STL字符串的STL向量
SWIG wrapping C++ for Python: translating a list of strings to an STL vector of STL strings
我想用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拉到全局命名空间中),等等。
相关文章:
- 将stl字符串缩小到小于15个字符的容量
- 使用 char 分隔符解析C++中的字符串,但将可重复的字符保留为每个解析的子字符串 (C++ STL) 中的分隔符
- 如何使用 STL 算法将整数向量转换为字符串向量?
- 为什么 stl 字符串C++函数有时出错有时会出错?
- 在 stl 中的字符串中擦除关键字的工作?
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- C++ wrt 字符串中的 STL 排序函数
- 将字符串流转换为 STL 容器
- 如何在不使用 STL 的情况下从函数反转字符串后返回字符串C++?
- 重新定义要在字符串的 STL 算法中使用的<运算符
- 从字符串(STL)中删除所有重复字符
- C++ STL 在逗号处拆分字符串
- 如何删除在没有STL的队列中存储在数组中的第一个字符串元素
- 寻找一种更有效的方法来使用 STL 函数检查字符串是否为回文
- C++STL字符串运算符+关联性
- 将字符串插入到c++stl集的时间复杂度
- 如何使用STL算法找到字符串中分隔两个不同字母的最短星号序列
- 使用stl替换嵌套的子字符串
- 循环访问字符串 (STL)
- c++转换成perl:如何使用c++11字符串STL函数