没有GIL,不允许来自Python的强制 我试图从这样定义的C++库调用函数: int somefunc(float timeout);
我在没有GIL,不允许来自Python的强制 我试图从这样定义的C++库调用函数: int somefunc(float timeout);,python,cython,gil,Python,Cython,Gil,我在pxd文件中加倍了定义: int somefunc(float timeout) nogil; timeout = 1.0 with nogil: Q.somefunc(timeout) 但是,在对pyx文件进行Cythonization操作时,任何使用nogil调用函数的尝试都会导致相同的错误: int somefunc(float timeout) nogil; timeout = 1.0 with nogil: Q.somefunc(timeout)
pxd
文件中加倍了定义:
int somefunc(float timeout) nogil;
timeout = 1.0
with nogil:
Q.somefunc(timeout)
但是,在对pyx
文件进行Cythonization操作时,任何使用nogil
调用函数的尝试都会导致相同的错误:
int somefunc(float timeout) nogil;
timeout = 1.0
with nogil:
Q.somefunc(timeout)
我还尝试使用ctype调用它,这会导致相同的错误
timeout = ctypes.c_float(1.0)
with nogil:
Q.somefunc(timeout)
只有使用浮点文本才有效。使用实际的Python变量调用此函数的正确方法是什么?当您查看生成的
timeout = 1.0
Q.somefunc(timeout)
您将看到,timeout
是PyObject
,调用\uuupyx\upyfloat\uasfloat
将is转换为cdef float。但是,在此转换过程中,可能会引发异常,因此需要gil,因此会显示错误消息
解决方案是在nogil块之前强制执行float
:
cdef float timeout = 1.0
with nogil:
Q.somefunc(timeout)
现在超时已经是cdef float,nogil块中不需要转换
稍微无关:我看不到代码和
Q
是什么,但大多数情况下,在让C/C++代码完成工作时释放gil是错误的:
Q
或其他数据)但是如上所述,它可能不适用于您的代码。是的,
cdef
确实有效。谢谢你的解释,这很有道理。我非常感谢关于是否解锁GIL的进一步讨论。在我的例子中,C++可以等待IO,不使用任何Python对象,只使用原始内存缓冲区。因此,我认为在这种情况下解锁GIL是合理的。