Reputation: 83
I have been working on extending a Python application using ctypes to call a shared library in C code. I have a boolean variable in Python which I would like to check periodically in an infinite loop in the C code to see if it changes. Is there a way to send the memory address of the python variable to the C function and access the content?
Thank you in advance!
Upvotes: 3
Views: 2723
Reputation: 155438
You can't pass a reference to an actual Python bool
. But you could make a ctypes.c_bool
, pass a pointer to it to your C code, and then have Python code assign it's .value
attribute to change the value from C's point of view.
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
Upvotes: 4