[Pyrex] A "main" function for Pyrex

Lenard Lindstrom len-l at telus.net
Sat Oct 2 00:43:04 CEST 2004


The Pyrex ToDo.txt file mentions an "Option for generating
a main() function?". Is this the same as C's main? If so
here is a way to turn a Pyrex module into a main program
using a reusable .pxi and .h file. No C stub program required.

This is an example Pyrex "main" program (embedded.pyx):

include "main.pxi"

def main(arglist):
    print "Hello from pyrex main version 4."
    print "My arguments are", arglist
    return 1



Parameter arglist is a python list; main's return value is
the program's return value.

Following is main.pxi:

cdef extern from "Python.h":
    void Py_Initialize()
    void Py_Finalize()
cdef extern from "pyxmain.h":
    void __pymoduleinit__()

# C program entry point.
# Call Pyrex 'pyx_main' entry point.    
cdef public int c_main "main" (int argc, char** argv):
    # Use only C variables and functions here.
    # Python application startup and terminate stuff.
    cdef int rval
    Py_Initialize()
    __pymoduleinit__()
    rval = pyx_main(argc, argv)
    Py_Finalize()
    return rval

# Pyrex program entry point.
# Call application specific Python 'main' entry point.
cdef int pyx_main(int argc, char** argv):
    # Convert between C and Python data types.
    cdef int c_rval
    cdef int argvidx

    args = []
    for argvidx from 0 <= argvidx < argc:
        args.append(argv[argvidx])
    rval = main(args)
    try:
       c_rval = rval
    except ValueError:
       c_rval = 0
    return c_rval


And this is pyxmain.h:

/* Expect macro __pymoduleinit__ to be defined.
   
   For versions of Python supporting DL_IMPORT/DL_EXPORT
   macros.
*/

#if !defined(DL_IMPORT) || !defined(DL_EXPORT)
#   error main.pxi: Unsupported version of Python/Pyrex
#endif
#undef DL_IMPORT
#undef DL_EXPORT
#define DL_IMPORT(typ) typ
#define DL_EXPORT(typ) typ

void __pymoduleinit__(void);


All that is needed is for the C macro __pymoduleinit__ to be defined
as the name of the python module init function (initembedded in the
above example). This can be done with an argument to the compiler. Or an
addition to the Pyrex compiler can put the macro definition at the
beginning of the generated C file.

Use pyrexc.py to compile the .pyx file. Compile the resulting C file
like any other Python embedded program. I hope this is of some use.

Lenard Lindstrom
<len-l at telus.net>






More information about the Pyrex mailing list