我正在使用SWIG为我的qt app生成Python Bindings。我有几个地方使用QList,我想整合SWIG图书馆中的std :: vector等QLists(见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();
};
到目前为止这种方法有效,但它并没有给我带来std :: vector的集成。
我无法找到std_vector.i,std_container.i的哪些部分,...使对象可迭代。
如何扩展QList接口文件以使我的QList可迭代?
答案 0 :(得分:1)
你要求的是 - 一个qlist.i swig文件,它在python中实现与QList
相同的集成度,就像std_vector.i对std::vector
所做的那样 - 是一项非常重要的任务
我提供了一个非常基本的扩展qlist.i文件(和qlisttest.i来向您展示如何使用它),并将尝试解释所需的步骤。
qlist.i
:
%{
#include <QList>
%}
%pythoncode %{
class QListIterator:
def __init__(self, qlist):
self.index = 0
self.qlist = qlist
def __iter__(self):
return self
def next(self):
if self.index >= self.qlist.size():
raise StopIteration;
ret = self.qlist.get(self.index)
self.index += 1
return ret
__next__ = next
%}
template<class T> class QList {
public:
class iterator;
typedef size_t size_type;
typedef T value_type;
typedef const value_type& const_reference;
QList();
size_type size() const;
void reserve(size_type n);
%rename(isEmpty) empty;
bool empty() const;
void clear();
%rename(add) push_back;
void push_back(const value_type& x);
%extend {
const_reference get(int i) throw (std::out_of_range) {
int size = int(self->size());
if (i>=0 && i<size)
return (*self)[i];
else
throw std::out_of_range("QList index out of range");
}
void set(int i, const value_type& val) throw (std::out_of_range) {
int size = int(self->size());
if (i>=0 && i<size)
(*self)[i] = val;
else
throw std::out_of_range("QList index out of range");
}
int __len__() {
return self->size();
}
const_reference __getitem__(int i) throw (std::out_of_range) {
int size = int(self->size());
if (i>=0 && i<size)
return (*self)[i];
else
throw std::out_of_range("QList index out of range");
}
%pythoncode %{
def __iter__(self):
return QListIterator(self)
%}
}
};
%define %qlist_conversions(Type...)
%typemap(in) const QList< Type > & (bool free_qlist)
{
free_qlist = false;
if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 0)) == -1) {
if (!PyList_Check($input)) {
PyErr_Format(PyExc_TypeError, "QList or python list required.");
SWIG_fail;
}
Py_ssize_t len = PyList_Size($input);
QList< Type > * qlist = new QList< Type >();
free_qlist = true;
qlist->reserve(len);
for (Py_ssize_t index = 0; index < len; ++index) {
PyObject *item = PyList_GetItem($input,index);
Type* c_item;
if ((SWIG_ConvertPtr(item, (void **) &c_item, $descriptor(Type *),0)) == -1) {
delete qlist;
free_qlist = false;
PyErr_Format(PyExc_TypeError, "List element of wrong type encountered.");
SWIG_fail;
}
qlist->append(*c_item);
}
$1 = qlist;
}
}
%typemap(freearg) const QList< Type > &
{ if (free_qlist$argnum and $1) delete $1; }
%enddef
qlisttest.i
:
%module qlist;
%include "qlist.i"
%inline %{
class Foo {
public:
int foo;
};
%}
%template(QList_Foo) QList<Foo>;
%qlist_conversions(Foo);
%inline %{
int sumList(const QList<Foo> & list) {
int sum = 0;
for (int i = 0; i < list.size(); ++i) {
sum += list[i].foo;
}
return sum;
}
%}
包装QList
以使其及其方法可从python中访问
这是通过使(部分)类定义可用于swig来实现的。这就是您当前的qlist.i
所做的事
注意:您可能需要为案例QList<T*>
添加“模板专精化”,因为您使用const_reference
,因此const T*
类型为QList
指针。否则,QList<T*>::const_reference
将const T*&
,显然可能会混淆swig。 (见swig/Lib/std/std_vector.i)
python列表与QList
之间的自动转换
这通常通过使用swig typemaps来实现。例如,如果您希望函数f(const QList<int>& list)
能够接受python列表,则需要指定一个输入类型映射来执行从python列表到QList<int>
的转换:
%typemap(in) const QList<int> &
{
PyObject * py_list = $input;
[check if py_list is really a python list of integers]
QList<int>* qlist = new QList<int>();
[copy the data from the py_list to the qlist]
$1 = qlist;
}
%typemap(freearg) const QList<int> &
{ if ($1) delete $1; }
在这里,情况在几个方面更加困难:
QList
的python列表或:为此,您需要在typemap中处理这两种情况。T
的python列表转换为QList<T>
:T
转换为普通T
。这是通过swig函数SWIG_ConvertPtr
实现的。%qlist_conversions(Type)
,您可以将其用于将类型图附加到特定QList<Type>
的{{1}}。对于其他转化方向(Type
- &gt; python列表),您应首先考虑您想要的内容。考虑一个返回QList
的C ++函数。从python调用它,它应该返回一个包装的QList<int>
对象,还是应该自动将QList
转换为python列表?
以python序列的形式访问包装的QList
,即使QList
和len
从python中工作
为此,您需要使用[]
扩展qlist.i文件中的QList
类,并实施%extend { ... }
和__len__
方法。
如果切片也应该有效,则需要为__getitem__
提供__getitem__(PySliceObject *slice)__
成员方法和输入以及“类型检查”类型图。
如果您希望能够使用python中的PySliceObject
修改已包装的QList
中的值,则需要实现[]
。
有关实现更好集成的所有有用方法的列表,请参阅“内置类型”和“容器的抽象基类”的python文档。
注意:如果您使用swig __setitem__
功能,则需要使用例如将上述功能注册到相应的“插槽”。
-builtin
从python中使包装的%feature("python:slot", "sq_length", functype="lenfunc") __len__;
迭代
为此,您需要扩展QList
类并实现一个返回python迭代器对象的QList
方法。
python迭代器对象是一个对象,它提供方法__iter__()
和__iter__()
(__next__()
用于较旧的python),其中next()
返回下一个值并引发python异常__next__()
表示结束。
如前所述,您可以在python或C ++中实现迭代器对象。我在python中展示了这样做的一个例子。
我希望这有助于您调整所需的功能。
答案 1 :(得分:0)
如docs所述,您需要以下内容:
__iter__()
中有一个方法,它返回一个迭代器对象(tp_iter
如果你在C中实现它)。__iter__()
并自行返回next()
,它返回下一个项目或者在完成后引发StopIteration
。 在python中做起来可能最简单,但你也可以在C中实现它。
另一种选择是使用python生成器来避免实现迭代器类型。为此,QList需要实现__iter__()
,但不是返回迭代器,而只是yield
值。
提到的方法只需要对python可见。您不必在C / Java中使用它们。
另见SWIG interfacing C library to Python (Creating 'iterable' Python data type from C 'sequence' struct)
答案 2 :(得分:0)
你提供了一个问题“如何使python对象可迭代”的答案,但我问“我如何扩展QList接口文件以使我的QList可迭代?”这更像是SWIG,而不是与python相关的问题。
我使用Java,C#和Python测试了http://www.swig.org/Doc1.3/Library.html#Library_nn15中的示例。只有Python和C#提供迭代器。生成的Java接口没有实现Iterable或类似的东西。据我所知,你的问题与目标语言有关。
也许延长MutableSequence是您的选择。您必须实现的唯一方法是__getitem__
,__setitem__
,__delitem__
,__len__
和insert
,方法是将它们委托给QList的相应方法。之后,您生成的类是可迭代的。