【问题标题】:Access to c pointer in python class from python method, cython从python方法cython访问python类中的c指针
【发布时间】:2017-04-14 09:49:43
【问题描述】:

在实现我的 python 集成的过程中,我遇到了一个问题。 我的课看起来像这样:

cdef class SomeClass:
    cdef CPPClass* cpp_impl

    def some_method(self):
        self.cpp_impl.cppMethod()

我有可以返回 CPPClass* 值的 cpp 类。像这样的:

class Creator
{
public:
    CPPClass* createClass();

}

所以我想像这样创建 SomeClass 实例:

cdef class PyCreator:
    cdef Creator* cpp_impl

    def getSomeClass(self):
        o = SomeClass()
        o.cpp_impl = self.cpp_impl.createClass()
        return o

但是我收到了 cython 无法将 CPPClass* 转换为 Python 对象的错误。 我该如何解决我的问题?谢谢。

【问题讨论】:

    标签: python c++ integration cython


    【解决方案1】:

    getSomeClass 中,它需要知道o 是什么类型,这样分配给cpp_impl 才有意义:

    def getSomeClass(self):
        cdef SomeClass o = SomeClass() # define the type
        o.cpp_impl = self.cpp_impl.createClass() # I think you missed a "self" here
        return o
    

    【讨论】:

    • 感谢您的回复。是的,我编辑了我的答案,因为我忘了使用self 这个词,但这不是我的问题。我的问题是我无法从 python 方法访问指针。
    • ...这是cdef SomeClass o = ... 应该做的。然后它知道o.cpp_impl 是一个CPPClass 指针,所以应该可以工作
    猜你喜欢
    • 2020-02-13
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2021-11-16
    • 1970-01-01
    相关资源
    最近更新 更多