pythoncffi

Canonical way to free string passed back from a c function in cffi?


ffi = FFI()
C = ffi.dlopen("mycffi.so")


ffi.cdef("""
char* foo(T *t);
void free_string(char *s);
""")

def get_foo(x):
    cdata = C.foo(x)
    s = ffi.string(cdata)
    ret = s[:]
    C.free_string(cdata)
    return ret

If I pass a char * from c function to python, python should free the memory. However, how should I do that?

My current workaround is to copy the string in python, and then free the string in C immediately. Hence Python can take care of the memory used by ret automatically.

What's the correct way to do that?


Solution

  • It turns out I don't need to copy s, s is already a copy of cdata

    def get_foo(x):
        cdata = C.foo(x)
        s = ffi.string(cdata)
        C.free_string(cdata)
        return s