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
{
public:
DBReader();
~DBReader();
};
#endif /* _DB_READER_H_ */
file: DBReader.cxx
#include "DBReader.h"
DBReader::DBReader()
{
std::cout << "Hello\n";
}
DBReader::~DBReader()
{
}
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()
file: setup.py
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 setup.py build_ext --inplace dbreader.so 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()
Hello
Hello
Hello
>>>
cython -amakes an annotated html page that helps link the C++ to Cython code. The constructor mechanism is slightly complex though - DavidW