[英]Cython c++ module, constructor called multiple times
I am trying to wrap my c++ class into python using Cython.我正在尝试使用 Cython 将我的 c++ 类包装到 python 中。 I am able to create the so file and import in python, but the constructor of my c++ class is called multiple time.
我能够在 python 中创建 so 文件并导入,但是我的 c++ 类的构造函数被多次调用。
This is what I have done so far.这是我迄今为止所做的。
file: DBReader.h文件:DBReader.h
#ifndef _DB_READER_H_
#define _DB_READER_H_
#include <iostream>
class DBReader
{
public:
DBReader();
~DBReader();
};
#endif /* _DB_READER_H_ */
file: DBReader.cxx文件:DBReader.cxx
#include "DBReader.h"
DBReader::DBReader()
{
std::cout << "Hello\n";
}
DBReader::~DBReader()
{
}
file: dbreader.pyx文件: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文件: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.运行
setup.py build_ext --inplace
dbreader.so 文件后创建。 And I am able to import in python.我可以在 python 中导入。 But as you can see below: Hello is printed thrice.
但正如您在下面看到的:Hello 被打印三次。
>>> import dbreader
>>> h = dbreader.PyDBReader()
Hello
Hello
Hello
>>>
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.通过添加这一行,您明确地构造了第二个这样的实例,然后将其复制到原始实例上,并且......我不确定这一切是如何工作的,但我猜是自动生成的复制构造函数正在调用第三次使用默认构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.