Wrapping Structures

Structures are similar to Python classes, except they do not contain any methods. They are the next element that you convert from C to Pyrex. To convert the structure:

  1. If needed, replace the typedef with a ctypedef,
  2. Write struct,
  3. Move the name of the structure from after the closing bracket (}) to after the struct,
  4. Remove ; from the end of each line, and
  5. Replace the {} blocking with a : and indenting.

CUPS

Structures will look something like the following (from the CUPS cups.h file).

typedef struct
{
  char *name;
  char *value;
} cups_option_t;

This is a structure, called cups_option_t, that holds two elements: name and value. The Pyrex version looks similar, including the types!

cdef extern from "cups/cups.h":
    ctypedef struct cups_option_t:
       char *name
       char *value

The first line tells Pyrex to include the file cups.h in the generated C file, much line the line we wrote earlier. The second line is quite different, however.

ctypedef
starts a typedef declaration,
struct
tells Pyrex that you are declaring a structure.
cups_option_t
is the name of the structure.

Structures can also hold other structures, just like C. For example:

    ctypedef struct cups_dest_t:
        char          *name
        char          *instance
        int           is_default
        int           num_options
        cups_option_t *options

The options value of the above structure holds a pointer to the cups_option_t structure we declared earlier.

You may want to try and compile the two structures above, linking against the cups library.

XOSD

External Structures

Some structures are external to the C header-file, so you do not know the elements in the structure. Declare these structures in much the same way as you would in C. Consider the following example, taken from xosd.h.

typedef struct xosd xosd;

In Pyrex it would look like the following.

  ctypedef struct xosd