gpt4 book ai didi

python - 从python方法cython访问python类中的c指针

转载 作者:行者123 更新时间:2023-11-28 05:24:12 24 4
gpt4 key购买 nike

在实现 Python 集成的过程中,我遇到了一个问题。我有这样的类(class):

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 对象。我该如何解决我的问题?谢谢。

最佳答案

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

关于python - 从python方法cython访问python类中的c指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com