在Cython中传递用户定义的类型

时间:2013-06-05 11:03:30

标签: c++ python oop cython

考虑以下示例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方法?

0 个答案:

没有答案
相关问题