Cython c ++模块,多次调用构造函数

时间:2018-03-25 07:54:43

标签: python c++ cython distutils cythonize

我正在尝试使用Cython将我的c ++类包装到python中。我能够在python中创建so文件并导入,但是我的c ++类的构造函数被多次调用。

这是我到目前为止所做的。
文件:RtlNodeGraphDBReader.h

#ifndef _RTLNODEGRAPHDB_READER_H_
#define _RTLNODEGRAPHDB_READER_H_

#include <iostream>

class RtlNodeGraphDBReader
{
  public:
    RtlNodeGraphDBReader();
    ~RtlNodeGraphDBReader();
};

#endif /* _RTLNODEGRAPHDB_READER_H_ */

文件:RtlNodeGraphDBReader.cxx

#include "RtlNodeGraphDBReader.h"

RtlNodeGraphDBReader::RtlNodeGraphDBReader()
{
  std::cout << "Hello\n";
}


RtlNodeGraphDBReader::~RtlNodeGraphDBReader()
{

}

file:nodegraph_dbreader.pyx

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

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

cdef class PyRtlNodeGraphDBReader:
    cdef RtlNodeGraphDBReader c_nodegraph_dbreader      # hold a C++ instance which we're wrapping
    def __cinit__(self):
        self.c_nodegraph_dbreader = RtlNodeGraphDBReader()

file:setup.py

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

modules = [Extension("nodegraph_dbreader",
                sources=["nodegraph_dbreader.pyx", "../RtlNodeGraphDBReader.cxx"],
                include_dirs = [".."],
                libraries = ["timecap"],
                library_dirs = ["/usr/local/lib64"],
                language = "c++")]

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

运行setup.py build_ext --inplace nodegraph_dbreader.so文件后创建。我可以在python中导入。但正如您所见:Hello打印三次。

>>> import nodegraph_dbreader
>>> h = nodegraph_dbreader.PyRtlNodeGraphDBReader()
Hello
Hello
Hello
>>>

1 个答案:

答案 0 :(得分:1)

这一行的问题:

self.c_nodegraph_dbreader = RtlNodeGraphDBReader()

如果你只想要一个默认构造的实例,那么你已经有了这个,没有这一行。

通过添加此行,您将明确构建第二个此类实例,然后将其复制到原始文件上,并且......我不确定这些内容是如何工作的,但我的猜测将是自动生成的复制构造函数第三次调用默认构造函数。