Wrapping C Functions

Now we have all the enumerations and structures declared we now have to wrap the C functions. In general, to convert a C function declaration to Pyrex you:

  1. Add cdef extern to the beginning of the line,
  2. Remove const keywords,
  3. Remove ; from the end of the line, and
  4. Replace (void) with ().
X
O
S
D

Consider the following C function declaration.

xosd *xosd_init (char *font, char *colour, int timeout, 
                 xosd_pos pos, int offset,
                 int shadow_offset);

It declares a function, xosd_init, which takes six arguments including one enumeration (pos). The Pyrex declaration of the same function looks very similar.

cdef extern xosd *xosd_init(char *font, char *colour, 
                            int timeout, xosd_pos pos, 
                            int offset, int shadow_offset)
extern
tells Pyrex that the function is defined elsewhere, but we are declaring it here.
xosd *
is what is returned by the function.
xosd_init
is the name of the function. This has to be the same as the name in the .h file.
(char *font, char *colour, int timeout, xosd_pos pos, int offset, int shadow_offset)
are the arguments.

Variable-Length Arguments

C, like Python, can handle variable length arguments. The conversion between C var-args and Pyrex var-args is fairly strait forward. Consider the function declaration:

int xosd_display (xosd *osd, int line, 
                  xosd_command command, ...);

After the three compulsory arguments (osd, line and command), the function xosd_display can take a variable number of arguments. To emulate this in Pyrex we also write ellipsis:

cdef extern int xosd_display(xosd *osd, int line,
                             xosd_command command, 
                             ...)

Be warned, things get more complicated later on.

C
U
P
S

Call by Reference

Call by reference is done in a similar way to call by value. Consider the following.

extern int cupsGetDests(cups_dest_t **dests);

Here dests will be modified when cupsGetDests returns. In Pyrex, the call would look like the following.

cdef extern int cupsGetDests(cups_dest_t **dests)

We have to have declared the argument, cups_dest_t, before we declared the function.

Previous Contents Next

Michael JasonSmith
Last modified: Mon Jun 24 11:55:28 NZST 2002