2

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?

1 Answer 1

4

When a pointer-object is created, it keeps a reference of the original object, thus preventing the original object from being destructed.

You can verify this behavior 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 is save to use.

Sign up to request clarification or add additional context in comments.

Comments

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.