In Cython, say I have a C function that returns a large buffer allocated with malloc() and expected to be freed later with free().
Now I need to pass this buffer to Python as a (bytes) str object, which would acquire ownership of it, and call free() later when the str object goes away. Is this possible and how?
Have a look at https://gist.github.com/1249305 for a implementation using numpy.
If numpy is not an option then something like this could work, using a memoryview:
Note the method
__dealloc__which will free the memory held by the pointer when all references to an instance ofBuffWrapdisappear and it gets garbage collected. This automatic deallocation is a good reason to wrap the whole thing in a class.I couldn’t figure out how one could use the returned pointer and use it for the buffer of, say, a bytearray. If someone knows, I’d be interested to see.