使C ++数组的对象在Python中是可迭代的 [英] Make C++ array of objects iterable in Python
问题描述
我在网上搜索,没有成功。我将下面的示例代码包装到Python(使用SWIG):
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
使用命令
But Python can't iterate over or access lista
using the comands
>>> 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,我使用SWIG 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 :: vector
或您自己类型的数组。
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;
}
可以用%template
, 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类型直观。您需要使用以下方法调用SWIG:
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一侧的行为直观,我给了一个详细示例。
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屋!