如何从 C 代码访问 python bool 变量?

How to access python bool variable from C code?

我一直致力于使用 ctypes 扩展 Python 应用程序以调用 C 代码中的共享库。我在 Python 中有一个布尔变量,我想在 C 代码的无限循环中定期检查它是否发生变化。有没有办法将python变量的内存地址发送给C函数并访问内容?

提前致谢!

您不能传递对实际 Python bool 的引用。但是您可以制作一个 ctypes.c_bool,将指向它的指针传递给您的 C 代码,然后让 Python 代码分配它的 .value 属性以从 C 的角度更改值。

from ctypes import *

# Flag initially false by default, can pass True to change initial value
cflag = c_bool()  

# Call your C level function, passing a pointer to c_bool's internal storage
some_c_func(byref(cflag))

# ... other stuff ...

# If C code dereferences the bool* it received, will now see it as true
cflag.value = True