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

Greg Ewing greg at cosc.canterbury.ac.nz
Mon Sep 22 05:11:02 CEST 2003


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

Exactly. You'll have to either copy the contents of the strings with
strdup or equivalent, or somehow ensure that references to the Python
strings are kept until the path array is no longer needed.

I'd recommend strduping them. Note that you'll need another function
to free the memory you've malloced for the array and strings when
you've finished with them.

> But also, I wonder if the <char**> -> <object> -> <char**> casting is
> the right way to do things.

NO, IT'S NOT! You should NEVER cast anything to a Python type
that isn't a genuine Python object. Extremely bad things will
happen if you do.

Presumably this function will only be used inside your extension
module, and not called directly from Python code. In that case,
it should be a C function, not a Python function:

  cdef char **build_parsed_path(path):

    ....

    return cpatharray

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

Yes, just store a Python reference to them somewhere, such as
in a module global, or an attribute of some object that you
know will stay alive long enough.

Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg at cosc.canterbury.ac.nz	   +--------------------------------------+




More information about the Pyrex mailing list