Cython c++ module, constructor called multiple times

I am trying to wrap my c++ class into python using Cython. I am able to create the so file and import in python, but the constructor of my c++ class is called multiple time.

This is what I have done so far.
file: DBReader.h

#ifndef _DB_READER_H_
#define _DB_READER_H_

#include <iostream>

class DBReader

#endif /* _DB_READER_H_ */

file: DBReader.cxx

#include "DBReader.h"

  std::cout << "Hellon";



file: dbreader.pyx

# distutils: language = c++
# distutils: sources = DBReader.cxx

cdef extern from "DBReader.h":
    cdef cppclass DBReader:
        DBReader() except +

cdef class PyDBReader:
    cdef DBReader c_dbreader      # hold a C++ instance which we're wrapping
    def __cinit__(self):
        self.c_dbreader = DBReader()


from distutils.core import setup, Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext

modules = [Extension("dbreader",
                sources=["dbreader.pyx", "../DBReader.cxx"],
                include_dirs = [".."],
                libraries = ["xxxx"],
                library_dirs = ["/usr/local/lib64"],
                language = "c++")]

setup(ext_modules = modules, cmdclass = {"build_ext" : build_ext})

After running build_ext --inplace file is created. And I am able to import in python. But as you can see below: Hello is printed thrice.

>>> import dbreader
>>> h = dbreader.PyDBReader()


The problem in this line:

self.c_nodegraph_dbreader = RtlNodeGraphDBReader()

If you just want a default-constructed instance, you’ve already got that, without this line.

By adding this line, you’re explicitly constructing a second such instance, and then copying that over the original, and… I’m not sure exactly how that’s all working, but my guess would be that the auto-generated copy constructor is calling the default constructor a third time.

Leave a Reply

Your email address will not be published. Required fields are marked *