C语言实现的Python扩展模块(兼容Python2 & 3)

来源:互联网 发布:大连理工大学 知乎 编辑:程序博客网 时间:2024/05/22 20:53

首先,一个完整的python2的C语言扩展模块开发及运行过程请参考文章:http://blog.csdn.net/zxygww/article/details/49097975。


#include <Python.h>//C functionint add(int arg1, int arg2){    return arg1 + arg2;}//add wrapped functionstatic 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 methodsstatic 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


0 0
原创粉丝点击