2016-10-21 3 views
1

구조체의 벡터를 반환하는 메서드가있는 C++ 클래스가 있습니다. 내 현재의 cython 구현에서 구조체는 괜찮 았지만 괜찮은 사전으로 끝나고, 나는 구조체를 파이썬 객체로 받고 싶습니다.객체를 cython으로 랩핑하다

현재 설정은 다음과 같습니다.

나에게 사전의 목록을 제공합니다 파이썬에서 myclass.myclass_function()를 호출이 경우

from libcpp.vector cimport vector 
cdef extern from "myheader.h": 
    cdef struct mystruct: 
     int mystruct_property 

    cdef cppclass myclass: 
     myclass() 
     vector[mystruct] myclass_function() 

mycode.pyx

cimport cpp_mycode 

cdef class myclass: 
    cdef cpp_mycode.myclass *thisptr 
    def __cinit__(self): 
     self.thisptr = new cpp_myclass.myclass() 
    def __dealloc(self): 
     if self.thisptr is not NULL: 
       delf self.thisptr 
    def myclass_function(self): 
     return self.thisptr.myclass_function() 

을 cpp_mycode.pxd, 각각은 키 'mystruct_property', which is functional, but a) it would be much better to be able to call it as a property .mystruct_property and also would be nice to be able to call a type`을 입력하고 의미있는 결과를 얻으십시오.

는 지금 내가 볼 수있는 유일한 해결책은 내 수업의 목록, 각각 __dict__.update 치료를 받고를 생산하기 위해 어떻게 든 self.thisptr.myclass_function()에 의해 반환 된 목록이 answer__dict__.update 일부를 사용하여 포장에서 온다. 그러나 이것을하기위한 더 우아하고 내장 된 cython 방식이 있어야한다고 생각합니다. 어떤 아이디어?

답변

1

구조체는 사전보다 더 낮은 수준의 데이터 유형이므로 원하는대로 유연하게 사용할 수는 없지만 구조체 또는 구조체 벡터에 대한 래퍼는 언제든지 __getattribute__, __setattr__과 같은 마법 메서드를 사용하여 작성할 수 있습니다. 항목에 액세스하십시오. 이것은 . 연산자가있는 구조체처럼 보이며 필드를 가져옵니다. 이 같은

뭔가 :

class Wrapper(): 
    def __init__(self, in_dict): 
     self.in_dict = in_dict 

    def __getitem__(self, key): 
     if key in self.in_dict: 
       return self.in_dict[key] 
     else: 
       return super().__getitem__(key) 

cdef class myclass: 
    ... 

    def myclass_function(self): 
     return map(Wrapper, self.thisptr.myclass_function()) 

은 아닌가요?

sturcts \ vectors (structs 구조체, structs 벡터 벡터 등)의 깊이가 확실하지 않은 경우 . -access 및 lists를 사용하여 구조체를 사전으로 재귀 적으로 변환하는 고유 한 함수를 만들 수 있습니다.

하지만 전환 수가 좋지 않다고 생각하세요. __getattribute__ - 액세스가 네이티브 __getitem__보다 느립니다.  

+0

솔루션은 원래 사전을 객체에 저장합니다.이 사전은 기본적으로 사전처럼 작동합니다. __getitem__은'[]'유형 호출을 구현하기 때문입니다. 이것은 타입을 검사 할 수있는 문제를 해결할 것이지만 실제로 struct와 같은 C로 만들지는 않습니다. – fbence