//bird.c
#include <Python.h>
#include <stdio.h>
void fly(const char *name) {
printf("%s is flying.\n", name);
}
static PyObject *bird_fly(PyObject *self, PyObject *args) {
const char *name;
if (!PyArg_ParseTuple(args, "s", &name)) return NULL;
fly(name);
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef bird_methods[] = {
{ "fly", bird_fly, METH_VARARGS, "Bird fly" },
{ NULL, NULL, 0, NULL }
};
PyMODINIT_FUNC initbird(void) {
PyImport_AddModule("bird");
Py_InitModule("bird", bird_methods);
}
编译
gcc -o bird.so `python-config --cflags` `python-config --libs` -shared -fPIC bird.c
#main.py
import bird
bird.fly("fwd")
位置关系
$ ls
bird.c bird.so main.py
$ python --version
Python 2.7.17
运行
$ python main.py
fwd is flying.