从 SWIG 绑定迭代 python 中返回的向量 <pair<int,int>>

iterate returned vector<pair<int,int>> in python from SWIG bindings

我发现这个问题和答案非常有用: Return vector<pair<int,int>> & from c++ method to python list of tuples using swig typemap

但是,如果 return 向量不是引用,我在迭代时遇到一些问题,这里是示例:

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 中正确迭代 returned 向量?为什么指向向量的指针 returned?我必须更改 swig 文件中的某些内容吗?

如果相关:(Ubuntu)

SWIG 无法正确理解 using 指令。

与本问答相同:

至于为什么要返回指针,嗯,如果 SWIG 无法将返回的对象转换为 python 对象,那么它会包装一个指向该对象的指针。