如何使用Python C API复制以下Python代码?
class Sequence():
def __init__(self, max):
self.max = max
def data(self):
i = 0
while i < self.max:
yield i
i += 1
Run Code Online (Sandbox Code Playgroud)
到目前为止,我有这个:
#include <Python/Python.h>
#include <Python/structmember.h>
/* Define a new object class, Sequence. */
typedef struct {
PyObject_HEAD
size_t max;
} SequenceObject;
/* Instance variables */
static PyMemberDef Sequence_members[] = {
{"max", T_UINT, offsetof(SequenceObject, max), 0, NULL},
{NULL} /* Sentinel */
};
static int Sequence_Init(SequenceObject *self, PyObject *args, PyObject *kwds)
{
if (!PyArg_ParseTuple(args, "k", &(self->max))) { …Run Code Online (Sandbox Code Playgroud) 我有一个模板化的c ++数组类,它使用标准的vector类:
#include <vector>
#include <string>
using namespace std;
template<typename T>
class Array1D{
private:
vector<T> data_;
int xsize_;
public:
Array1D(): xsize_(0) {};
// creates vector of size nx and sets each element to t
Array1D(const int& nx, const T& t): xsize_(nx) {
data_.resize(xsize_, t);
}
T& operator()(int i) {return data_[i];}
T& operator[](int i) {return data_[i];}
};
Run Code Online (Sandbox Code Playgroud)
我的SWIG界面文件看起来像
%module test
%{
#define SWIG_FILE_WITH_INIT
#include "test.h"
%}
%include "std_vector.i"
// Array 1D Typemaps
// typemaps for standard vector<double>
namespace std{
%template(DoubleVector) vector<double>; …Run Code Online (Sandbox Code Playgroud) 我正在使用 SWIG 为我的 qt 应用程序生成 Python 绑定。我有几个地方使用QList,我想从 SWIG 库中集成像 std::vector 这样的QList(参见http://www.swig.org/Doc1.3/Library.html#Library_nn15)。
这意味着:
为了实现这一点,我使用以下代码:https :
//github.com/osmandapp/OsmAnd-core/blob/master/swig/java/QList.i
后来在我使用 QLists 的课程中,我添加了如下代码:
%import "qlist.i"
%template(listfilter) QList<Interface_Filter*>;
class A {
public:
//.....
QList<Interface_Filter*> get_filters();
};
Run Code Online (Sandbox Code Playgroud)
到目前为止,这有效,但它没有给我与 std::vector 的那种集成。我无法找出 std_vector.i、std_container.i、... 的哪些部分使对象可迭代。
我需要如何扩展 QList 接口文件才能使我的 QList 可迭代?
Collection我有一个管理 a std::vector<Element>(该类的私有成员)的C++ 类。
在 C++ 中,我可以使用begin()和end()迭代器(它们只是vector's 迭代器的类型定义)来迭代向量,如下所示:
Collection col;
for (Collection::const_iterator itr = col.begin(); itr != col.end(); itr++)
{
std::cout << itr->get() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
现在我希望用 Python 做类似的事情,例如:
import example
el = example.Element()
el.set(5)
col = example.Collection()
col.add(el)
for e in col:
print e.get()
Run Code Online (Sandbox Code Playgroud)
但这会导致:
类型错误:“集合”对象不可迭代
我无法以生成__iter__Python 类(我认为这是它唯一需要的)的方式配置 SWIG Collection。我该怎么做?
这是我的代码:
示例.h:
#include <vector>
class Element
{
public:
Element();
~Element();
int get() const;
void set(const int var);
private: …Run Code Online (Sandbox Code Playgroud)