1

考虑以下我想通过 Cython 向 Python 公开的示例 C++ 类。AProducer创建 aProduct并传递给 a 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方法吗?

4

0 回答 0