2012-01-17 6 views
3

웹에서 검색했지만 성공하지 못했습니다. 나는 (꿀꺽 꿀꺽 사용) 파이썬에 아래의 샘플 코드를 포장하고 있습니다 :파이썬에서 객체의 C++ 배열을 반복 가능하게합니다.

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); 
    }; 
}; 

그러나 파이썬은 반복 할 수 없거나 액세스 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 반복 가능한 만들 수 있습니까? C++ 배열 대신 파이썬 목록을 사용하는 방법이 있습니까?

내 파이썬 버전은 3.2이며, 나는 4.6.1

감사

g ++로 꿀꺽 꿀꺽 2.0.4을 사용하고
+0

'list (test.lista)' – rplnt

답변

2

std::vector 또는 자신 만의 유형을 사용하려는 경우 질문에 약간의 불확실성이 있습니다. 주어진 std::vector를 들어

, 일부 C++와 같은 :

#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.istd_vector.i 예컨대 : 파이썬 유형에 직관적으로 작동합니다

%module test 

%{ 
#include "test.h" 
%} 

%include "pyabc.i" 
%include "std_vector.i" 

%include "test.h" 

%template (FooVector) std::vector<foo>; 

으로 포장 할 수 있습니다. 당신은 같은과 SWIG를 호출해야합니다 : 생각 나는 이전의 대답에 detailed example을 준 파이썬 측면에서 직관적으로 행동 할 수있는 "사용자 정의"용기를 래핑하는 것입니다

swig -python -c++ -py3 -extranative test.i

합니다.

1

대신 C++/꿀꺽 꿀꺽 측의 파이썬 측에이 문제를 해결 할 수 있습니다 간단.

# wrapper/facade 
class Funa: 
    def __init__(self): 
     self._impl = myModule.funa() # _impl => implementation 

    def __iter__(self): 
     for i in xrange(3): 
      yield self._impl.lista[i] 

test = Funa() 
for x in test: 
    print(x) 
+0

@ user1154091 : 파이썬에서 내부 루프를 유지하는 한 속도가 너무 빨라지지 않습니다. 내부 루프를 C++ 코드로 이동시켜 실제로 효과를냅니다. –

+0

@Sven Marnach : 이것은 동일한 오류를 보여주는 단순한 코드 조각입니다. 내 실제 코드의 병목 현상은 클래스'atomo'의 인스턴스입니다. –

+0

@CaioS : 위의 내 의견은 너무 느릴 수 있으므로이 대답이 마음에 들지 않는다는 (지금 삭제 된) 댓글에 대한 응답이었습니다. –

0

larsmans 유사한 접근법이 Funa.__iter__ 발전기 객체를 반환한다. 그런 다음 SWIG가 생성 한 인터페이스에 추가하기 만하면됩니다. (자신의 포장으로, 당신은 다른 모든 방법을 포장 할 것이다, 또는 __getattr__로 재생할 수 있습니다.) 대략 그것은 %extend%pythoncode 지시어를 사용하여 꿀꺽 꿀꺽 파일에 삽입하는 것이 더 간단해야한다이

class Funa: 

    class FunaIter : 
    def __init__(self, parent) : 
     self.parent = parent 
     self.pos = 0 

    def __iter__(self) : 
     while self.pos < 3 : 
     yield self.parent.lista[self.pos] 
     self.pos += 1 

    def __iter__(self) : 
    return self.FunaIter(self) 

이 같은 것입니다.

또한 SWIG has wrappers for STL containers을 사용하면 이러한 항목을 사용하여 필요한 항목을 쉽게 얻을 수 있습니다.

관련 문제