Daniel Standage
Daniel Standage

Reputation: 8314

Initialize C++ object with arguments from Cython constructor

I have implemented a filter class in C++, and I am working on wrapping this with Cython for use in Python. The Cython MyFilter class currently looks like this.

cdef class MyFilter:
    cdef filter f;
    def __cinit__(self, list array_sizes):
        cdef vector[size_t] as = array_sizes
        self.f.init(as)
    def add(self, uint32_t value):
        self.f.add(value)
    def get(self, uint32_t value):
        return self.f.get(value)

Originally, the C++ class had a single constructor which took a std::vector<size_t> as an argument. But to make the Cython wrapper work, I had to define a default argument-less constructor and then add an init() function to initialize the object once the arguments were available from the __cinit__ constructor. This added some unwanted complexity to the C++ code.

Is there are cleaner or better way of doing this? I'd like to avoid pointers if necessary, but might be convinced with a compelling argument.

Upvotes: 2

Views: 1050

Answers (1)

Matt Ostlund
Matt Ostlund

Reputation: 229

Actually, your solution IS the cleaner better way :)

The other solution is just to add an overloaded constructor, that you can then call from init.:

cdef cppclass myclass:
    myclass() except +
    myclass(args) except +

Then add to your python class

cdef class myPyClass:
    cdef myclass pclass
    def __cinit__(self,args):
        pclass = new myclass(args)        

Upvotes: 1

Related Questions