首先,一个完整的python2的C语言扩展模块开发及运行过程请参考文章:http://blog.csdn.net/zxygww/article/details/49097975。
#include <Python.h>
//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}
};
#if PY_MAJOR_VERSION >= 3
// The method table must be referenced in the module definition structure.
static struct PyModuleDef sampleModule = {
PyModuleDef_HEAD_INIT,
"sample", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
wrap_methods
};
// The initialization function must be named PyInit_name()
PyMODINIT_FUNC PyInit_sample(void)
{
return PyModule_Create(&sampleModule);
}
#else
//initilization function named init<modulename>
PyMODINIT_FUNC initsample(void)
{
Py_InitModule("sample", wrap_methods);
}
#endif