Let's say I want to pass a pointer to int
to a C function from Python using ctypes:
from ctypes import *
lib = CDLL("./myLib.so")
i = c_int(50)
pi = pointer(i)
lib.myfunc(pi)
No problem with this code. But let's say I do this instead:
from ctypes import *
lib = CDLL("./myLib.so")
pi = pointer(c_int(50))
lib.myfunc(pi)
What happens regarding the garbage collector? In the first example the pointed contents were referenced through the i variable. But I'm not sure if they are in the second one. There is no variable referencing those contents. Can it be garbage collected? Or the sole fact that the pointer is pointing at it makes the contents safely allocated?
When a pointer
-object is created, it keep a reference of the original object, thus preventing it of being destructed.
You can verify it with the following code:
from ctypes import *
import sys
i = c_int(50)
print(sys.getrefcount(i)) # => 2 - a reference from i and one as argument of sys.getfrefcount
pi = pointer(i)
print(sys.getrefcount(i)) # => 3 - additional reference is saved in pi
del pi
print(sys.getrefcount(i)) # => 2 again - the reference from pi was cleared
that means, also in the second version there will be no dangling pointer and it save to use.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments