我正在使用 SWIG 为我的 qt 应用生成 Python 绑定(bind)。我有几个地方使用 QList s,我想集成 SWIG 库中的 std::vector 之类的 QList(参见 http://www.swig.org/Doc1.3/Library.html#Library_nn15)。
这意味着:
- QList 对象应该是可从 python 迭代的(=它们必须是可迭代的 python 对象)
- 应该可以将 python 列表传递给采用 qlist 的函数
- ... 以及 std::vector 的 SWIG 库中列出的所有其他功能
为此,我使用以下代码:
https://github.com/osmandapp/OsmAnd-core/blob/master/swig/java/QList.i
稍后在使用 QLists 的类(class)中,我添加如下代码:
%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 接口(interface)文件以使我的 QList 可迭代?
最佳答案
您要的是一个 qlist.i swig 文件,它实现了与 QList
相同的集成级别在 python 中,就像 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*>
添加“模板特化” typedefconst_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; }
这里的情况在几个方面更加困难:
- 您希望能够传递一个 python 列表或一个包装的
QList
:要使其正常工作,您需要在类型映射中处理这两种情况。 - 你想转换一个包装类型的 python 列表
T
到QList<T>
:
这还涉及从包装类型T
转换列表的每个元素。到平原T
.这是通过 swig 函数实现的SWIG_ConvertPtr
. - 我不确定您是否可以使用模板参数指定类型映射。因此,我写了一个 swig 宏
%qlist_conversions(Type)
您可以使用它来将类型映射附加到QList<Type>
对于特定的Type
.
对于其他转换方向(
QList
-> python list)你应该首先考虑你想要什么。考虑一个返回QList<int>
的 C++ 函数.从 python 调用它,这应该返回一个包装的QList
对象,还是应该自动转换QList
到 python 列表?- 您希望能够传递一个 python 列表或一个包装的
访问包装的
QList
作为 python 序列,即 makelen
和[]
从 python 工作
为此,您需要扩展QList
使用%extend { ... }
在 qlist.i 文件中上课并实现__len__
和__getitem__
方法。如果切片也应该起作用,您需要提供
__getitem__(PySliceObject *slice)__
PySliceObject
的成员方法和输入以及“类型检查”类型映射如果您希望能够修改包装的
QList
中的值使用[]
从 python,你需要实现__setitem__
.有关您可以实现以实现更好集成的所有有用方法的列表,请参阅有关“内置类型”和“容器的抽象基类”的 python 文档。
注意:如果您使用 swig
-builtin
功能,那么您需要使用例如将上述功能额外注册到适当的“插槽”%feature("python:slot", "sq_length", functype="lenfunc") __len__;
制作包裹
QList
可从 python 迭代
为此,您需要扩展QList
类并实现__iter__()
返回 python 迭代器对象的方法。Python 迭代器对象是提供方法
__iter__()
的对象。和__next__()
(next()
对于较旧的 python),其中__next__()
返回下一个值并引发 python 异常StopIteration
结束。如前所述,您可以使用 Python 或 C++ 实现迭代器对象。我展示了一个用 Python 执行此操作的示例。
我希望这有助于您作为调整所需功能的基础。
关于python - swig:如何使 QList<T> 可迭代,如 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30863728/