Home > Net >  Two Python objects holding the same C pointer in ctypes
Two Python objects holding the same C pointer in ctypes

Time:08-11

Say I have a class with a C pointer instance variable. I have to de-allocate the pointer memory when the class is deleted, which I do with __del__

class foo():
    def __init__(self, ptr):
        self.my_ptr = ptr
    def __del__(self):
        CFuncDeallocatingMemory(self.my_ptr)

Now, I create two objects of this class with the same pointer

ptr = CFuncReturningPointer()
bar1 = foo(ptr)
bar2 = foo(ptr)

And delete one of the objects (not necessarily explicitly, but say I'm going out of scope...)

del bar1

Then the other object's pointer memory has also been deallocated! (of course, it's the same pointer...). How would I go about preventing one object going out of scope deallocating the pointer memory, while still deallocating the pointer memory when both objects are deleted?

That is, how can I

  1. ensure pointer memory is deallocated when both objects exit scope and the pointer is no longer needed
  2. at the same time allow for both objects to hold the exact same pointer, without one object going out of scope freeing the memory

What I am describing is kind of like a C shared_ptr.

I want the memory deallocation to be handled by the class itself, and not explicitly by the user (i.e. the user calling CFuncDeallocatingMemory when both objects exit scope)

CodePudding user response:

Don’t wrap the pointer in foo twice. Just do bar2 = bar1 and let Python reference count the foo object.

  • Related