Make C++ array of objects iterable in Python

会有一股神秘感。 提交于 2019-12-04 12:40:49
Flexo

It's a little unclear from your question if you want to use std::vector or an array of your own types.

For std::vector, given some C++ like:

#include <vector>
#include <string>

struct foo {
  std::string name;
};

inline std::vector<foo> test() {
  std::vector<foo> ret;
  foo instance;
  instance.name = "one";
  ret.push_back(instance);
  instance.name = "two";
  ret.push_back(instance);
  return ret;
}

You can wrap it with %template, pyabc.i and std_vector.i e.g.:

%module test

%{
#include "test.h"
%}

%include "pyabc.i"
%include "std_vector.i"

%include "test.h"

%template (FooVector) std::vector<foo>;

which will behave intuitively on the Python type. You'll need to call SWIG with something like:

swig -python -c++ -py3 -extranative test.i

If the idea is to wrap a "custom" container to behave intuitively on the Python side I gave a detailed example in a previous answer.

You might want to solve this on the Python side instead of the C++/SWIG side for simplicity.

# wrapper/facade
class Funa:
    def __init__(self):
        self._impl = myModule.funa()   # _impl => implementation

    def __iter__(self):
        for i in xrange(3):
            yield self._impl.lista[i]

test = Funa()
for x in test:
    print(x)
AFoglia

A similar approach to larsmans is to have Funa.__iter__ return a generator object. Then you would only need to add to the interface SWIG creates. (With his wrapping, you would have to wrap every other method, or play with __getattr__.) Roughly it would be like this

class Funa:

  class FunaIter :
    def __init__(self, parent) :
      self.parent = parent
      self.pos = 0

    def __iter__(self) :
      while self.pos < 3 :
        yield self.parent.lista[self.pos]
        self.pos += 1

  def __iter__(self) :
    return self.FunaIter(self)

This should be simpler to insert into your SWIG file using the %extend and %pythoncode directives.

Also, SWIG has wrappers for STL containers, so perhaps using those, you can easily obtain the necessary item getters.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!