启用profile时含指针的Cython ctuple编译失败求解决方案
Cython启用profile=True时含指针的ctuple编译失败的替代解决方案
当启用profile=True时,Cython编译包含返回指针类型ctuple的扩展类方法会失败,已缩小问题范围,示例代码如下:
%%cython -a #cython: profile=True cdef class Foo: cdef: int bar def __init__(self): self.bar = 0 cdef (int*,) foobar(self): return (&self.bar,)
经测试得出以下结论:
- 若
foobar定义在扩展类外,可正常编译 - 若ctuple包含
int而非int*,可正常编译 - 含指针的多元素ctuple(如
(int, int*))仍编译失败
以下是除打包为结构体之外的可行解决方法:
1. 使用固定大小的指针数组作为返回类型
Cython在profile模式下对数组的支持更稳定,可将ctuple替换为固定大小的指针数组:
%%cython -a #cython: profile=True cdef class Foo: cdef: int bar def __init__(self): self.bar = 0 cdef int*[1] foobar(self): int*[1] result result[0] = &self.bar return result
使用时通过索引result[0]即可访问目标指针。
2. 采用输出参数传递结果
将返回的指针通过传入的指针参数传递,避免返回ctuple:
%%cython -a #cython: profile=True cdef class Foo: cdef: int bar def __init__(self): self.bar = 0 cdef void foobar(self, int** out_ptr): if out_ptr is not NULL: *out_ptr = &self.bar
调用时传入一个指针的指针,即可接收目标指针的值。
3. 单独禁用该方法的Profiling
如果该方法不需要被Profiling统计,可给方法添加nogil修饰符,绕过profile模式下的ctuple指针编译问题:
%%cython -a #cython: profile=True cdef class Foo: cdef: int bar def __init__(self): self.bar = 0 cdef (int*,) foobar(self) nogil: return (&self.bar,)
注意:此方法会让该方法脱离全局Profiling统计,需根据实际需求选择。
内容的提问来源于stack exchange,提问作者Todd Sierens
相关产品推荐
相关产品推荐

