Setting a custom free function for returned pointers

86 views
Skip to first unread message

William Roberts

unread,
Apr 21, 2021, 10:58:47 AM4/21/21
to python-cffi
I currently have a calling scheme in a C library that takes a double pointer and returns the allocated data through the double pointer. How do I set the destructor for the C allocated structure? I tried ffi.gc to no avial. Details below.

struct bar {
   int a;
   int b;
   int c;
};

int foo(struct bar **x) {
   struct bar *n = custom_new();
   n->a = 1;
   n->b = 2;
    n->c = 3;
    *x = n;
   return 0;
}

In python  CFFI we call the routine like so

def py_foo() {
  x = ffi.new('struct bar **')
  lib.foo(x)
  return x[0]
}

How do we set a free function for x[0]? I tried using ffi.gc like so:
ffi.gc(x[0], lib.custom_free)

but that bombed.





Armin Rigo

unread,
Apr 22, 2021, 1:30:30 AM4/22/21
to pytho...@googlegroups.com
Hi William,

On Wed, 21 Apr 2021 at 16:59, William Roberts <bill.c....@gmail.com> wrote:
> How do we set a free function for x[0]? I tried using ffi.gc like so:
> ffi.gc(x[0], lib.custom_free)
>
> but that bombed.

Every call to x[0] returns a new CFFI pointer object (pointing to the
same thing). Additionally, ffi.gc() returns yet another pointer
object (again pointing to the same thing). That's the one that must
be kept alive in Python. So:

return ffi.gc(x[0], lib.custom_free)

will call lib.custom_free(y) at some point after the pointer returned
by this py_foo() function is forgotten.


A bientôt,

Armin.

William Roberts

unread,
Apr 22, 2021, 11:12:27 AM4/22/21
to pytho...@googlegroups.com
Thank you Armin for that clear explanation. It seems to be working, I am seeing calls to the libraries free functions as expected.
 

A bientôt,

Armin.

--
-- python-cffi: To unsubscribe from this group, send email to python-cffi...@googlegroups.com. For more options, visit this group at https://groups.google.com/d/forum/python-cffi?hl=en
---
You received this message because you are subscribed to a topic in the Google Groups "python-cffi" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/python-cffi/DROgzjrCwE4/unsubscribe.
To unsubscribe from this group and all its topics, send an email to python-cffi...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python-cffi/CAMSv6X0jkrr4u3%2BtRnu2PAEuii3_O%2B9T-rfmnbnxEjBjDoXkyA%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages