2008年9月10日水曜日

python-c api programming

i ve tried to copile python-c code a dozen times. but everytime, i failed.
i didn't know why it does'nt work. the code is very simple like just showing "Hello World!".
the problem was how to compile. a compiler always returned " undefined reference to `_imp__PyArg_ParseTuple'".
i though it's a liker problem.
today, i finally succeeded to do it!!! this is a memo for it.

at this time, i used following simple code from [2].

ext.c

#include

static PyObject *
fact(PyObject *self, PyObject *args)
{
int n;
int i;
int ret=1;

if (!PyArg_ParseTuple(args, "i", &n))
return NULL;

for (i=n; i>0; i--) ret *= i;

return Py_BuildValue("i", ret);
}

static PyObject *
hello(void)
{
printf("Hello World!!\n");
Py_RETURN_NONE;
}

static char ext_doc[] = "C extention module example\n";

static PyMethodDef methods[] = {
{"hello", hello, METH_VARARGS, "print hello world.\n"},
{"fact", fact, METH_VARARGS, "return factorial.\n"},
{NULL, NULL}
};

void initext(void)
{
Py_InitModule3("ext", methods, ext_doc);
}




gcc -IC:\Python25\include -LC:\Python25\libs ext.c -lpython25 -shared -o ext.pyd


that's it!!!you can import as "ext" on python command line!


reference:
[1] http://techtonik.rainforce.org/2008_01_01_archive.html
[2] http://f59.aaa.livedoor.jp/~ookini/pukiwiki.php?Python%A4%CEC%B8%C0%B8%EC%B3%C8%C4%A5%A5%E2%A5%B8%A5%E5%A1%BC%A5%EB%A4%F2%BB%C8%A4%C3%A4%C6%A4%DF%A4%EB

0 件のコメント: