C言語実現のPython拡張モジュール
1332 ワード
file: sample.c
#include //C function int add(int arg1, int arg2) { return arg1 + arg2; }//add wrapped function static PyObject* wrap_add(PyObject *self, PyObject *args) { //Convert the python input objects into C objects int arg1, arg2; if(!PyArg_ParseTuple(args, "ii", &arg1, &arg2)) return NULL; //Call c function int result = add(arg1,arg2); //wrap the result from c function to python object. return (PyObject*)Py_BuildValue("i", result); }//define the PyMethodDef methods static PyMethodDef wrap_methods[] ={ {"add", wrap_add, METH_VARARGS}, {NULL, NULL} };//initilization function PyMODINIT_FUNC initsample(void) { Py_InitModule("sample", wrap_methods); }
注意:Cファイル名sampleとPyMODINIT_FUNC initsample(void)およびPy_InitModule(「sample」の赤い部分が一致している必要があります.
1、コード:
上記のコードの赤い部分は必要に応じて修正する必要があり、他の部分は固定されています.
2、コンパイル:
gcc -fpic -c -I /usr/include/python2.7 test.c
gcc -shared -o test.so test.o
3、python運転
pythonコマンドラインで次の操作を行います.
>>> import test
>>> test.add(1,2)
リファレンス
:
http://www.ibm.com/developerworks/cn/linux/l-pythc/index.html
http://bbs.chinaunix.net/thread-1593255-1-1.html