它本质上是这个问题的延伸 - Usage of threadpoolexecutor in conjunction with cython's nogil
在这种情况下,我的 getArea2() 方法略有不同
cdef int getArea2(self,double[:] p) nogil:
cdef int area
cdef SphericalPoint spoint
spoint = SphericalPoint()
area = 0
area = self.rect.getArea()
return area
并且 .pxd 声明略有不同
cdef extern from "Point.h":
cdef cppclass SphericalPoint(Point):
SphericalPoint() except +
double getCoordinate1()
double getCoordinate2()
void setCoordinate1(double lat)
void setCoordinate2(double lon)
这样我就得到了这些编译错误。对象的实例化有什么原因不正确吗?
我尝试将 spoint 作为指针并实例化该对象,但它给了我同样的错误
cdef SphericalPoint *spoint
spoint = new SphericalPoint()
编译 Cython 文件时出错:
cdef int getArea2(self,double[:] p) nogil:
cdef int area
cdef SphericalPoint spoint
spoint = SphericalPoint()
^
------------------------------------------------------------
test.pyx:78:30: Calling gil-requiring function not allowed without gil
最佳答案
这是一个非常简单的问题:Cython 假设任何函数都需要 GIL,除非您另有说明。在 pxd 声明中:
SphericalPoint() nogil except +
您可能也想将 nogil
添加到其他成员函数中。
我最初认为问题出在 except +
注释上。这会导致 Cython 捕获任何 C++ 异常并将其转换为 Python 异常。这确实需要 GIL,但前提是捕获到异常,并且 Cython 会自动处理此问题,因此不必担心。另一种方法是由于未处理的 C++ 异常而导致整个程序崩溃,因此您确实需要保留 except +
。
关于c++ - 使用 C++ 时,如果没有 gil 编译错误,则不允许调用需要 gil 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57247759/