cython - 是否可以在 Cython 中编写 "pure"c++ 类?

标签 cython

在Cython中,一个类,或者说一个扩展类型就是一个Python类,这意味着它可以被Python初始化。另一方面,其__init____cinit__的参数必须是Python对象。

是否可以在 Cython 中编写一个只能由 cdef 函数初始化的类,从而可以由 C 类型和 C++ 对象初始化?

我想要这样做是因为将我现有的 Python 代码转换为 Cython 代码比 C/C++ 代码更容易。

最佳答案

您可以很容易地创建一个不能(很容易)从 Python 初始化的类,但只能从 cdef 工厂函数创建

cdef class ExampleNoPyInit:
    cdef int value

    def __init__(self):
        raise RuntimeError("Cannot be initialise from python")

cdef ExampleNoPyInit_factory(int v):
    cdef ExampleNoPyInit a

    # bypass __init__
    a = ExampleNoPyInit.__new__(ExampleNoPyInit) 
    a.value = v
    return a

inst = ExampleNoPyInit_factory(5)

(我怀疑真正的 promise 者可以使用相同的方法在 Python 中初始化它,如果他们愿意的话。还有其他方法可以防止初始化,如果你想更彻底 - 例如你可以在你的 Cython 中使用 cdef 全局变量模块作为标志,不能从 Python 访问)。

这个类仍然有内置的 Python 引用计数机制,所以仍然是一个“Python 类”。如果你想避免这种情况,那么你可以使用 cdef struct,(尽管它不能有成员函数)。

关于cython - 是否可以在 Cython 中编写 "pure"c++ 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36258343/

相关文章:

ipython - 如何将 Cython 模块导入 IPython Notebook 并进行编译

python - 将 cython 中的 numpy 数据分配给 View

python - 是否需要在 Cython 中显式删除动态分配的容器(如 std::vector)

python - Cython + OpenCV 和 NumPy

python-3.x - 使用打印函数参数编译 cython 错误

arrays - 将Numpy数组传递给用Cython包装的C代码

python - 是否可以在没有 Visual Studio 许可证的情况下在 Windows 上编译 Cython 模块用于商业目的?有哪些替代方案?

vim - Vim 的标签列表中是否支持 Cython?

python - 在 cython : defining ndarray datatype/ndims 中使用 numpy

python - 我可以通过 gsl_function 的包装或 cython 重新声明将 cython 类方法分配给 gsl_function 结构吗?