【问题标题】:iterate returned vector<pair<int,int>> in python from SWIG bindings从 SWIG 绑定中迭代返回的向量<pair<int,int>>
【发布时间】: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


    【解决方案1】:

    SWIG 无法正确理解 using 指令。

    与此问答相同: SWIG argument error when using "using std::vector" in python

    至于为什么返回指针,好吧,如果 SWIG 不能将返回的对象转换为 python 对象,那么它会包装一个指向该对象的指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 2018-04-01
      • 2014-07-14
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多