python编写和调用c接口

之前研究使用了python调用c函数,时间长了容易忘记,今天写个例程记录下,先预览readme.md内容。

# readme.md

# python c api module

## create your c files and write your functions

like, test_pyc.c, test_mutip.c

## write c functions

like,

```

int test_add(int a, int b)

{

    int c = a + b;

    printf("a = %d\r\n", a);

    printf("b = %d\r\n", b);

    printf("a + b = %d\r\n", c);

    return c;

}

```

---

## create python c wrapper file

like, test_pyc_module.c

---

write wrapper functions, like

```

/**

 * int test_add(int a, int b) wrapper

 */

static PyObject *py_test_add(PyObject *self, PyObject *args)

{

    int a, b;

    // python类型的 args 转换成C类型 a,b

    if(!PyArg_ParseTuple(args, "ii", &a, &b)) {

        return NULL;

    }

    // C类型转换成python类型

    return (PyObject*)Py_BuildValue("i", test_add(a, b));

}

```

## wrap methods

```

static PyMethodDef py_test_methods[] = {

    {"test_add", (PyCFunction)py_test_add, METH_VARARGS, NULL},

    {NULL,NULL}

};

```

## wrap module

```

/**

 * {PyModuleDef_HEAD_INIT, "module_name", "module description", -1, module_methods}

 */

static struct PyModuleDef py_test_methods_module = {

    PyModuleDef_HEAD_INIT,

    "test_module",

    "python c api test methods module",

    -1,

    py_test_methods

};

```

## define init function

```

/**

 * py module init

 *

 * defined like below:

 * PyMODINIT_FUNC

 * PyInit_xxx(void)

 * {

 *

 * }

 *

 * xxx is as same as PyModuleDef module_name

 */

PyMODINIT_FUNC

PyInit_test_module(void)

{

    PyObject *mod;

    mod = PyModule_Create(&py_test_methods_module);

    if(mod == NULL) {

        return NULL;

    }

    return mod;

}

```

# install module

## write setup.py

```

# -*- coding:utf-8 -*-

# terminal run: python setup.py install

from distutils.core import setup, Extension

MOD = "test_module" # defined in test_pyc_module.c

# sources_list = [include called c files, use "," to split]

sources_list = ['test_pyc_module.c','test_pyc.c', 'test_multip.c']

setup(name=MOD,

      version="1.0",

      description="python c api test module",

      ext_modules=[Extension(MOD, sources=sources_list)]

      )

```

## excute in terminal

$python setup.py install

例程见附件:

GitHub - xiaosimple/python_c_api_sample: python c api module sample


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值