[Pyrex] Passing references to C "objects,structures,arrays,etc"

John J Lee jjl at pobox.com
Mon Sep 22 03:19:49 CEST 2003


On 21 Sep 2003, Seth Nickell wrote:

> I'm wrappering the DBus API, which uses a number of complex/annoying

The verb 'to wrap' already exists, Seth -- you don't need to reinvent it
from its noun <wink>.


> types. I want to write simple converter functions for these which take a
> nice Python type and produce an appropriate C type. For example, the
[...]
> I'd really like to have a function:
>
> def build_parsed_path(path):
>     cdef char **cpatharray
[...]
>     return <object>cpatharray
>
> And then on the client side...
>
> cdef char **cpatharray
> path_array = build_parsed_path("/my/test/path")
> cpatharray = <char**>path_array
>
> But this doesn't work, cpatharray[0] on the client side ends up being
> totally different from cpatharray[0] inside build_parsed_path. My guess
> is that "cpatharray[i] = path_element" gets a reference to internal
> memory of path_element rather than strdup-ing, which is gargbage
> collected when path_element_list goes out of scope?

So strdup it or Py_INCREF it or keep a reference in a list, I guess?

cdef extern from "Python.h":
    void Py_INCREF(object)
    void Py_DECREF(object)
    void Py_XINCREF(object)
    void Py_XDECREF(object)


You can always check what's really going on by looking at the generated C
code.  It's not too painful to read, though it is rather verbose.


> But also, I wonder if the <char**> -> <object> -> <char**> casting is
> the right way to do things.
>
> 1) Is there a more natural way to pass around C pointers to functions
> and stuff that doesn't require this nasty casting? Is the casting even
> valid or is this maybe what's causing the corruption?

Why are you doing that?  What's stopping you just keeping it as a char **?


> 2) Is there a way to "ref" Python objects so that they won't be gargbage
> collected when there are C pointers pointing to all or pieces of them?

See above.


John





More information about the Pyrex mailing list