考虑以下示例C ++类,我想通过Cython向Python公开。 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;
}
};
这是*.pyx
文件中的Python包装器代码。
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
方法?