2
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?

4

1 回答 1

2

原来我不需要复制ss已经是cdata

def get_foo(x):
    cdata = C.foo(x)
    s = ffi.string(cdata)
    C.free_string(cdata)
    return s
于 2017-06-09T10:05:37.013 回答