python - 将 C++ 指针作为参数传递给 Cython 函数

标签 python cython

cdef extern from "Foo.h":
    cdef cppclass Bar:
        pass

cdef class PyClass:
    cdef Bar *bar

    def __cinit__(self, Bar *b)
        bar = b

这总是会给我类似的东西:
无法将 Python 对象参数转换为类型 'Bar *'

有没有办法做到这一点,或者我需要从 Bar 对象中提取所有内容,创建一个 Python 等效项,将其传入,然后在 PyClass 中重建它>?

最佳答案

我在尝试将带有结构的 C 代码包装为 python 类时遇到了这个问题。问题似乎是“特殊”函数,包括 __init____cinit__ 必须声明为 def 而不是 cdef .这意味着它们可以从普通的python中调用,因此类型参数被有效地忽略了,一切都被视为对象。

在 J.F. Sebastian 的回答中,修复不是包装—— double 是基本的数字类型,因此 C/C++ 类型和 Python 对象之间存在默认转换。 Czarek 的回答基本上是正确的——你需要使用一个假的构造函数,使用一个全局函数。不能使用 @staticmethod 装饰器,因为它们不能应用于 cdef 函数。在提供的原始示例中,答案看起来更简单。

cdef extern from "Foo.h":
    cdef cppclass Bar:
        pass

cdef class PyClass:
    cdef Bar *bar

cdef PyClass_Init(Bar *b):
    result = PyClass()
    result.bar = b
    return result

关于python - 将 C++ 指针作为参数传递给 Cython 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12204441/

相关文章:

python - Cython 尝试编译两次,但失败了

windows - python 3.4 : compile cython module for 64-bit windows

Python 打包 : Boost library as dependency

Python: "unsupported operand types for +: ' long' 和 'numpy.float64' "

python - setuptools.find_packages 中的 "where"参数是什么?

Python 2.7 - 评估列表中的元素以在 for 循环中使用

cython - Cython 中 dealloc 中的 Python 对象

python - 赛通: "Cannot convert Python object"错误

python - 将表从 google bigquery 导出到 google storage

Python 三元搜索算法