1

Cython 経由で Python に公開したい次の C++ クラスの例を考えてみましょう。Aは、に渡される をProducer作成します。ProductConsumer

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