[Pyrex] Assign C object to a cdeffed variable of a class

Lenard Lindstrom len-l at telus.net
Sat Sep 8 19:05:44 CEST 2007


Stefano Esposito wrote:
> Hi all,
>
> i'm trying to write a python bindings to a library in pyrex (this is my first try in usin pyrex).
>
> I hava a C function declared (in the .h file) as this:
>
>   int alpm_pkg_load (const char *filename, pmpkg_t **pkg);
>
> and which i've declared to pyrex as follows:
>   ing alpm_pkg_load (char *filname, pmpkg_t **pkg);
>
> the pmpkg_t is an exter struct and i've declared it as:
>
>   ctypedef struct pmpkg_t
>
> i have defined a class like follows:
>
>   cdef class Package:
>      cdef pmpkg_t *pkg
>      [...]
>
> what i'd like to do is to call the alpm_pkg_load from a module function like:
>
>   def package_new_from_file (filename):
> 	cdef pmpkg_t *pkg
> 	
> 	alpm_pkg_load (filename, &pkg)
>
> and then assing the pkg variable to the pkg member of Package class. I've tried with simply:
>
> 	pypkg = Package()
> 	pypkg.pkg = pkg
>
> but pyrexc complains to cannot convert pmpkg_t (*) to a Python object. Is there a way to do something similar or a work around?
>
>   
cdef Package pypkg
pypkg = Package()
py pkg.pkg = pkg

But why? Is it not more sensible for package_new_from_file to return a 
Package object?

def package_new_from_file(filename):
    cdef Package pypkg
    cdef pmpkg_t *pkg
    alpm_pkg_load(filename, &pkg)
    pypkg = Package()
    pypkg.pkg = pkg
    return package

Better still, if alpm_pkg_load is the only way to create a pmpkp_t then 
call it from the Package constructor.

cdef class Package:
    cdef pmpkg_t *pkg
    
    def __new__(self, filename):
        cdef pmpkg_t *pkg

        alpm_pkg_load(filename, &pkg)

Then:

pypkg = Package(filename)

Now all Package instances will be valid from the start.

-- 

Lenard Lindstrom
<len-l at telus.net>




More information about the Pyrex mailing list