"""
Experiment with embedding Python via Pyrex
"""
# get stuff we need from C header files
cdef extern from "stdio.h":
int printf(char *format,...)
cdef extern from "Python.h":
# embedding funcs
void Py_Initialize()
void Py_Finalize()
void PySys_SetArgv(int argc, char **argv)
# declare any other Python/C API functions we might need
void Py_INCREF(object o)
void Py_DECREF(object o)
object PyString_FromStringAndSize(char *, int)
# ... etc etc...
# IMPORTANT - we need to explicitly prototype the function
# 'init<mymodulename>()', where 'mymodulename' is the
# filename this code resides in. I called the file 'testpyx.pyx',
# hence the name below
cdef public void inittestpyx()
# With all this out of the way, we can declare any amount of
# Pyrex python extension types, and regular python classes/functions
cdef class Testclass:
cdef public int someint
cdef public char *somestring
def __init__(self):
self.someint = 43
self.somestring = "this is a string"
def hello(self):
print "Hello, this is an instance of %s" % self.__class__.__name__
# Now, need to declare the needed C main() function
cdef public int main(int argc, char **argv):
# warm up python
Py_Initialize()
# Setup sys.argv
PySys_SetArgv(argc, argv)
printf("initialising testpyx\n")
inittestpyx() # mandatory
# Initialisation done - we can now do Python stuff
printf("testmain: instantiating Testclass\n")
testobj = Testclass()
printf("testmain: created testobj\n")
print "testobj.someint = %s" % testobj.someint
print "testobj.somestring = %s" % testobj.somestring
print "calling testobj.hello()"
testobj.hello()
# clean up before we leave - this probably isn't strictly necessary
print "cleaning up"
Py_Finalize()