How does cffi pointer get free?

281 views
Skip to first unread message

Yicong Huang

unread,
May 21, 2015, 3:07:08 AM5/21/15
to pytho...@googlegroups.com
Here is a typical case:
In python, we use cffi to new a char* pointer:
charp = ffi.new("char []", ret)
And then the pointer charp return to C code. To prevent charp GC by PyPy before it really acess in C cdoe, we might put charp to a global list:
noGCList.append(charp).

And here are questions:
1. Could the pointer get free in C code? 
2. If C code write "free (charp)", as in Python charp keep alive by noGCList, I think it is safe. But if noGCList is clean later, will it casue "double free" issue when PyPy try to GC charp?


Armin Rigo

unread,
May 21, 2015, 3:44:57 AM5/21/15
to pytho...@googlegroups.com
Hi Yicong,
No, the C code cannot free() a ffi.new() object. If you want to send
memory from Python to C, with the C code responsible for free()ing,
then you must call malloc() in the first place:

ffi.cdef("""... char *malloc(size_t); char *strcpy(char*, char*); ...""")

p = lib.malloc(len(mystring) + 1)
lib.strcpy(p, mystring)


A bientôt,

Armin.

Yicong Huang

unread,
May 21, 2015, 5:06:28 AM5/21/15
to pytho...@googlegroups.com
We did some experiments and found out we should *not* free pointer from Python cfii in C.
When PyPy gc happen, it would lead to "double free" issue.
Things we could do in C code to handle pointer:
1. Callback python to remove the pointer from list, and let Python to recyle the object by GC sometime later
2. Explictly callback python gc.collect() to incur gc (we might not do such things unless memory hungry for a large object allocation)
Reply all
Reply to author
Forward
0 new messages