迭代返回的向量<;配对<;int,int>&燃气轮机;在python中,来自SWIG绑定
我发现这个问题和答案非常有用: 但是,如果返回向量不是引用,我在迭代它时会遇到一些问题,例如: myclass.h:迭代返回的向量<;配对<;int,int>&燃气轮机;在python中,来自SWIG绑定,python,c++,vector,swig,iterable,Python,C++,Vector,Swig,Iterable,我发现这个问题和答案非常有用: 但是,如果返回向量不是引用,我在迭代它时会遇到一些问题,例如: myclass.h: #include <vector> #include <utility> using std::vector; using std::pair; class MyClass { private: vector<pair<int,int> > _myvector; public: MyClass( );
#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;
};
但当我在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
回溯(最近一次呼叫最后一次):
文件“Test.py”,第6行,在
对于b中的a,b。GetMyVector()
TypeError:“SwigPyObject”对象不可编辑
如何在python中正确迭代返回的向量?为什么返回指向向量的指针?我必须更改swig文件中的某些内容吗
如果相关:(在Ubuntu上)
- SWIG版本2.0.11
- g++(Ubuntu 4.9.4-2ubuntu1~14.04.1)4.9.4
- Python 2.7.6
- SWIG无法正确理解
指令的使用
与本问答相同:
至于返回指针的原因,如果SWIG无法将返回的对象转换为python对象,那么它将封装指向该对象的指针。SWIG无法正确理解指令
与本问答相同:
至于返回指针的原因,如果SWIG无法将返回的对象转换为python对象,那么它将封装指向该对象的指针
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
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