通过C来扩展Python
Python是一门通过C语言写出来的动态语言。那么可以通过C语言对Python3的库进行扩展。
主要的流程是通过C语言实现一些方法和功能,然后使用Python.h的文件功能,将C语言实现的功能进行包装,通过gcc编译城*.so的库文件。然后在python的代码中import编译成功的库,就可以调用库里面的方法了。
下面是C的代码:
首先,通过c语言定义几个函数fact(), zero()和add()。然后对这几个函数进行包装,在本文例子中是通过wrap_fact(),wrap_zero()和wrap_add()将三个函数包装。文件存为main.c(名字可以随便定义为*.c)
#include <Python.h>
int fact(int n)
{
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
void zero()
{
int result = 0;
}
int add(int a, int b)
{
return a+b;
}
PyObject* wrap_fact(PyObject* self, PyObject* args)
{
int n, result;
if (! PyArg_ParseTuple(args, "i", &n))
return NULL;
result = fact(n);
return Py_BuildValue("i", result);
}
PyObject* wrap_zero(PyObject* self, PyObject* args)
{
if(!PyArg_ParseTuple(args, ""))
return Py_BuildValue("", NULL);
zero();
return Py_BuildValue("", NULL);
}
PyObject* wrap_add(PyObject* self, PyObject* args)
{
int a, b;
if (!PyArg_ParseTuple(args, "ii", &a, &b))
return Py_BuildValue("i", 0);
int result = add(a, b);
return Py_BuildValue("i", result);
}
static PyMethodDef exampleMethods[] =
{
{"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
{"zero", wrap_zero, METH_VARARGS, ""},
{"add", wrap_add, METH_VARARGS, ""},
{NULL, NULL}
};
void initexample()
{
PyObject* m;
m = Py_InitModule("example", exampleMethods);
}
接着,通过gcc -fPIC -o example.so -shared -I/usr/include/python2.7 main.c 将文件编译为example.so的库
接下来,通过在python中导入原来的库就可以将原来文件进行调用了。
import example print example.fact(4) example.zero() print example.add(3,4)


浙公网安备 33010602011771号