Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 658
colinfang Avatar asked Nov 25 '25 11:11

colinfang


1 Answers

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
like image 82
colinfang Avatar answered Nov 27 '25 00:11

colinfang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!