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

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

本文关键字:lt int gt vector pair 中的 SWIG 绑定 返回 python 迭代      更新时间:2023-10-16

我发现这个非常有用的问题和答案:返回 vector<int,int>> & from c++ 方法到 python 使用 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
  • 蟒蛇 2.7.6

SWIG不能正确理解using指令。

与本问答相同:在python中使用"using std::vector"时出现SWIG参数错误

至于为什么返回指针,

好吧,如果 SWIG 无法将返回的对象转换为 python 对象,那么它会包装指向该对象的指针。