Рассмотрим следующий пример классов C ++, которые я хочу представить в Python через Cython. Producer
создает Product
который передается Consumer
,
class Product {
public:
Product() : x(42) {
}
Product(int xin) : x(xin) {
}
int x;
};class Producer {
public:
Product create(int xin) {
Product p(xin);
return p;
}
};
class Consumer {
public:
void consume(Product p) {
std::cout << p.x << std::endl;
}
};
А вот код оболочки Python в *.pyx
файл.
cdef extern from "CythonMinimal.h":
cdef cppclass _Product "Product":
_Product() except +
_Product(int x) except +
int x
cdef extern from "CythonMinimal.h":
cdef cppclass _Producer "Producer":
_Producer() except +
_Product create(int x)
cdef extern from "CythonMinimal.h":
cdef cppclass _Consumer "Consumer":
_Consumer() except +
void consume(_Product p)cdef class Product:
cdef _Product instance
cdef setInstance(self, _Product instance):
self.instance = instance
def getX(self):
return self.instance.x
cdef class Producer:
cdef _Producer instance
def create(self, x):
p = Product()
cdef _Product _p = self.instance.create(x)
p.setInstance(_p)
return p
cdef class Consumer:
cdef _Consumer instance
def consume(self, product):
self.instance.consume(product.instance)
Так что мне удалось вернуть мои пользовательские объекты с помощью setInstance
метод, но я пока не могу передать объекты. Consumer.consume
метод не работает:
cls ~ $ python3 setup.py build
running build
running build_ext
cythoning CythonMinimal.pyx to CythonMinimal.cpp
Error compiling Cython file:
------------------------------------------------------------
...
cdef class Consumer:
cdef _Consumer instance
def consume(self, product):
self.instance.consume(product.instance)
^
------------------------------------------------------------
CythonMinimal.pyx:41:31: Cannot convert Python object to '_Product'
Можете ли вы предложить исправление для consume
метод?
Задача ещё не решена.
Других решений пока нет …