Using `SafeHandle` for a C API, that includes reference counting

139 views Asked by At

I am working on Python interop. Internally, Python keeps reference counters for all objects via Py_IncRef and Py_DecRef. I want to ensure proper finalization of pointers to Python objects, so I am trying to create a class PyHandle derived from SafeHandle, that would call Py_DecRef on ReleaseHandle.

Problem is: unlike, for example, Windows API, Python does not increment refcount before returning a pointer to an object. So when interop creates an instance of PyHandle, I want it to call Py_IncRef on the pointer. However, I do not see a method I could override for that to happen. SafeHandle constructor takes invalid handle value, and there is no AcquireHandle to override. CoreCLR code also has non-overridable SetHandle method (see SafeHandle.cs).

What can I do to make the call to Py_IncRef when PyHandle is constructed by interop?

Is SafeHandle the right tool for the task?

1

There are 1 answers

1
Marcel On

SafeHandle has no public method to pass a handle to it. So feel free to call Py_IncRef before you pass the handle to the protected base methods.

However, SafeHandle might be somewhat overkill for your purpose as it maintains its own reference counter which is not really required for a handle that maintains it's own reference count.