从C调用python函数作为回调函数。处理GIL的正确方法是什么?

2024-09-24 12:27:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用cytpes来包装一个C api。其中一个api函数允许您注册回调。我使用CFUNCTYPE来指定函数的类型,并从python库的用户提供的python函数中生成一个CFUNCTYPE的实例,然后将其传递给C函数(用ctypesapi调用)。在

我知道ctypes调用会释放GIL。我想知道当C库函数调用python回调函数时会发生什么。ctypes是否重新获得{}?在

documentation上写着:

Note: Make sure you keep references to CFUNCTYPE() objects as long as they are used from C code. ctypes doesn’t, and if you don’t, they may be garbage collected, crashing your program when a callback is made. Also, note that if the callback function is called in a thread created outside of Python’s control (e.g. by the foreign code that calls the callback), ctypes creates a new dummy Python thread on every invocation. This behavior is correct for most purposes, but it means that values stored with threading.local will not survive across different callbacks, even when those calls are made from the same C thread.

它没有提到GIL。这是否意味着一切都由我来处理?在


Tags: the函数fromyouapithatisas
1条回答
网友
1楼 · 发布于 2024-09-24 12:27:19

回调的_objects属性中引用的^{}具有C库调用的pcl_exec函数指针。这段代码使用thunk的引用调用^{},再加上调用args和一个指向内存的指针来存储结果。闭包函数反过来调用^{},thunk的restypesetfunccallableconverters和{}作为参数。_CallPythonObject做的第一件事是调用^{}获取GIL。即使这是Python第一次看到当前线程,也可以这样做。在

换句话说,这一切都是为你处理的。只需保留对回调的引用以保持thunk的引用。在

相关问题 更多 >