On Sun, Apr 19, 2009 at 6:56 AM, Mohamed Lrhazi <[email protected]> wrote:
> is there a way to avoid that by compiling the foo.pyx
> directly into native executable?
There's no way to get rid of the Python interpreter, but you could
embed the interpreter and statically link your module. This has two
main advantages: (1) you only have a single file to deal with, rather
than the script and the .so, and (2) you can profile using `gprof',
which does not work with shared objects.
Here's an example:
--------------------------------- mylib.pyx --------------------------
import sys
cdef extern from "math.h":
double lgamma(double)
double exp(double)
cdef inline double gamma(double n):
return exp( lgamma(n) )
def main(argv = None):
if argv is None:
argv = sys.argv
if len(argv) != 2:
name = argv[0] if argv else '<prog>'
sys.stderr.write("USAGE: %s n\nPrints gamma(n).\n" % name)
sys.exit(1)
print gamma(float(argv[1]))
----------------------------------------------------------------------
----------------------------------- main.c ---------------------------
#include <Python.h>
// For each Cython module you want to embed, you must declare an
// init<module> function, like so:
PyMODINIT_FUNC initmylib(void);
int
main(int argc, char *argv[])
{
// The first step is to set up the Python interpreter:
Py_Initialize();
PySys_SetArgv(argc, argv);
// Next, we need to tell Python that our module exists. Call each
// of the functions you declared above.
initmylib();
// Now do some Python stuff. The easiest thing to do is to give
// the interpreter a string of Python code that imports your
// module and calls it.
PyRun_SimpleString("from mylib import main\n"
"main()\n");
// When we're done, tell Python to clean up.
Py_Finalize();
return 0;
}
----------------------------------------------------------------------
On my machine, I compile with:
cython mylib.pyx
gcc -fPIC -g -O2 -I /usr/include/python2.5 -c -o main.o main.c
gcc -fPIC -g -O2 -I /usr/include/python2.5 -c -o mylib.o mylib.c
gcc -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions \
main.o mylib.o /usr/lib/python2.5/config/libpython2.5.a \
-lm -ldl -pthread -lutil \
-o main
(See http://docs.python.org/extending/embedding.html for details on
how to properly compile.)
Now I can run my program as a normal executable:
$ ./main
USAGE: ./main n
Prints gamma(n).
$ ./main 6
120.0
$ ./main 100
9.33262154439e+155
--
Mark
_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev