I am trying to build my fisrt python extension, using Cython.

My C files are partitioned logically, and the functionality is "nested" - in that module C depends on functions defined in module B, which then depends on module A.

I am finding it difficult to understand how to partition my .pxd and .pyx files so that I can maintain the depency between functional modules.

The following snippet, hopefully should help clarify the situation:

Note: The file FooBar.h includes a file CommonDefs.h which declares common data types and provides a simple API for these common types (myArray and mySet).

I have already created ccommontypes.pxd and commontypes.pyx files which export the data types and functions declared/defined in CommonDefs.h and CommonDefs.c. I was able to succesfully compile a python extension module from that.

I now want to move to the next stage which is to export the data types and functions which have a dependency on CommonDefs.h. However, I find that I am having to redeclare the types myArray and mySet (even though they were already declared in ccommontypes.pxd

I can't seem to find anyway of importing or including those declarations, so I am having to re-declare them in the file below, as the functions take arguments of type myArray and mySet.

Question 1 Is it ok to redeclare the types again as I have done below or are there any gotchas I need to be aware of?

//cfoobar.pxd
cdef extern from "../include/FooBar.h":
    cdef struct FooBar:
        pass

    ctypedef struct myArray:   // already declared elsewhere
        pass

    ctypedef struct mySet:     // Already declared elsewher
        pass

    struct FooBar * foobar_new(mySet *s1)


//foobar.pyx
cimport cfoobar

cdef class FooBar:
    cdef cfoobar.FooBar *_foobar
    def __cinit__(self, myset):
        _foobar = cfoobar.foobar_new(myset);
        if (ret == 0):
            raise MemoryError()

Question 2 From the FooBar ctor code above, the memory allocation function expects a pointer to a mySet variable. However, when I attempt to compile this code, I get this error:

Cannot convert Python object to 'mySet *'

I understand the error message, but since Python is not statically typed, I don't know how I can specify the data type.

I would appreciate some help on resolving this.

1

There are 1 best solutions below

0
On

I came across this question while trying to sort out redeclaration issues in pxds myself... I believe there must be some "gotchas" but I won't venture yet to say what they are. :)

But to question 2: python is dynamically typed but cython is not ... just that variables without types are statically typed as python objects.

You can change:

def __cinit__(self, myset):

to:

def __cinit__(self, mySet *myset):

if you are really passing in a pointer to a myset...