【发布时间】:2017-03-16 12:46:02
【问题描述】:
我发现这个非常有用的问题和答案: Return vector<pair<int,int>> & from c++ method to python list of tuples using swig typemap
但是,如果返回向量不是参考,我在迭代返回向量时会遇到一些问题,这里是示例:
myclass.h:
#include <vector>
#include <utility>
using std::vector;
using std::pair;
class MyClass {
private:
vector<pair<int,int> > _myvector;
public:
MyClass( );
const vector<pair<int,int> > & GetMyVector() const;
};
myclass.cpp:
#include "myclass.h"
MyClass::MyClass(): _myvector()
{_myvector.push_back(std::make_pair(1,2));_myvector.push_back(std::make_pair(1,2));};
const vector<pair<int,int>> & MyClass::GetMyVector() const {
return _myvector;
};
myclass.i:
%module x
%include <std_pair.i>
%include <std_vector.i>
%include <std_string.i>
%template() std::pair<int,int>;
%template(PairVector) std::vector<std::pair<int,int> >;
%{
#include "myclass.h"
%}
%include "myclass.h"
编译:
g++ -std=c++11 -c -fPIC myclass.cpp
swig -c++ -v -python myclass.i
g++ -std=c++11 -fPIC -c myclass.cpp myclass_wrap.cxx -I/usr/include/python2.7
g++ myclass.o myclass_wrap.o -shared -fPIC -o _x.so
但是当我在 python 中运行这样的东西时:
import x
b=x.MyClass()
print(b.GetMyVector())
for a,b in b.GetMyVector():
print(a,b)
然后我得到:
<Swig Object of type 'vector< std::pair< int,int >,std::allocator< std::pair< int,int > > > *' at 0x7ff06804b1b0>
Traceback (most recent call last):
File "Test.py", line 6, in <module>
for a,b in b.GetMyVector():
TypeError: 'SwigPyObject' object is not iterable
如何在 python 中正确地迭代返回的向量?为什么返回一个指向向量的指针?我必须更改 swig 文件中的某些内容吗?
如果相关:(在 Ubuntu 上)
- SWIG 版本 2.0.11
- g++ (Ubuntu 4.9.4-2ubuntu1~14.04.1) 4.9.4
- Python 2.7.6
【问题讨论】:
标签: python c++ vector swig iterable