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

11 篇文章 0 订阅
1 篇文章 0 订阅

首先,一个完整的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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值