5

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?

1 Answer 1

6

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 its .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
Sign up to request clarification or add additional context in comments.

3 Comments

I tried this but the C code is not able to "see" the change that the Python code performed on the variable.
@EduMoga: How is the C code declared? If it's not declaring the argument as a volatile bool* (perhaps some sort of atomic), the optimizer could easily be caching the value from memory to a register once and never rereading the memory (I'm assuming threads are involved here, since otherwise the infinite loop in C would never return to Python, so Python would never get a chance to change the bool).
Thank you, I fixed the issue using a multiprocessing.Value object to use the c_bool in order to be able to access it from C code and be able to see the change reflected. The original question did not include the multiprocess/multithread issue so I marked the answer as correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.