【发布时间】:2013-10-14 22:20:36
【问题描述】:
我正在尝试包装两个 C++ 类:Cluster 和 ClusterTree。 ClusterTree 有一个方法 get_current_cluster() 实例化一个 Cluster 对象,并返回一个对它的引用。 ClusterTree 拥有 Cluster 对象,并在 C++ 中管理它的创建和删除。
我已经用 cython 包装了 Cluster,从而生成了 PyCluster。
PyCluster 应该有两种创建方式:
1) 通过传入两个数组,这意味着 Python 应该自动处理删除(通过 __dealloc__)
2) 通过直接传入原始 C++ 指针(由 ClusterTree 的 get_current_cluster() 创建)。在这种情况下,ClusterTree 然后承担删除底层指针的责任。
这会导致:
编译 Cython 文件时出错: -------------------------------------------------- ---------- ... def get_current_cluster(self): cdef Cluster* ptr = &(self.__thisptr.getCurrentCluster()) 返回 PyCluster.__constructFromRawPointer(ptr) ^ -------------------------------------------------- ---------- terran.pyx:111:54:无法将“集群 *”转换为 Python 对象注意我不能 cdef __init__ 或 @classmethods。
【问题讨论】:
-
你调用的函数必须是
cdef。如果 Cython 不支持cdef classmethod,那么您将需要使用classmethod以外的其他内容。 -
另外,您的类方法尝试修改
__thisptr,这是一个实例变量,而不是类变量。由于这个原因,类方法的第一个参数通常是cls,而不是self。 -
不是 cdef 的变量总是实例变量吗?我以为 cdef Cluster* __thisptr;将 __thisptr 声明为实例变量。 @classmethods 不允许修改实例变量吗?
-
类方法不能修改实例变量;他们甚至无法访问实例(只有类)。