让C ++对象数组迭代在Python [英] Make C++ array of objects iterable in Python
问题描述
我有搜索在网络上并没有获得成功。我包裹在下面的示例code到Python(使用痛饮):
I have searched on the web and didn't get success. I'm wrapping the sample code below to Python (using SWIG):
class atomo {
public:
int i;
atomo(int a) {
i = a;
};
};
class funa {
public:
atomo *lista[3];
funa() {
lista[0] = new atomo(1);
lista[1] = new atomo(2);
lista[2] = new atomo(3);
};
};
但使用命令对应的Python不能遍历或访问 LISTA
>>> test = myModule.funa()
>>> test.lista[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __iter__
TypeError: 'SwigPyObject' object is not subscriptable
>>> for i in test.lista:
>>> print(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __iter__
TypeError: 'SwigPyObject' object is not subscriptable
我怎样才能让 LISTA
迭代?有使用Python列表而不是C ++数组的方式?
How can I make lista
iterable? There is a way to use Python lists instead of C++ arrays?
我的Python版本是3.2,我使用痛饮2.0.4使用g ++ 4.6.1
My Python version is 3.2 and I'm using SWIG 2.0.4 with g++ 4.6.1
感谢
推荐答案
,如果你想使用的从你的问题有点不清楚的std ::矢量
或数组自己的类型。
It's a little unclear from your question if you want to use std::vector
or an array of your own types.
有关的std ::矢量
,给出了一些C ++这样的:
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;
}
您可以用%模板
, pyabc.i
和 std_vector.i把它包
例如:
%module test
%{
#include "test.h"
%}
%include "pyabc.i"
%include "std_vector.i"
%include "test.h"
%template (FooVector) std::vector<foo>;
这将直观地表现在Python类型。你需要调用痛饮的东西,如:
which will behave intuitively on the Python type. You'll need to call SWIG with something like:
swig -python -c++ -py3 -extranative test.i
如果这个想法是包装一个自定义容器直观表现在Python的身边,我给了一个<一个href=\"http://stackoverflow.com/questions/8776328/swig-interfacing-c-library-to-python-creating-iterable-python-data-type-from/8828454#8828454\">detailed例如的在previous答案。
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.
这篇关于让C ++对象数组迭代在Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!