用c扩展python
来源:互联网 发布:水银知乎 编辑:程序博客网 时间:2024/06/10 14:45
搞了一晚上终于做了一个demo,也会用distutils做一个包了,不过现在太晚了,先睡觉,明天好好做下笔记;
写一个简单得python c扩展一共就那么几步,
1。 编写c函数
int math_fib(int n){ if (n<=2) return 1; return math_fib(n-1) + math_fib(n-2);}
2. 编写一个包装函数
static PyObject*spam_fib(PyObject *self, PyObject *args){ int n, result; if (!PyArg_ParseTuple(args, "i", &n)) return NULL; result = math_fib(n); return Py_BuildValue("i", result);}
3. 模块函数数组
static PyMethodDef SpamMethods[] = { {"system", spam_system, METH_VARARGS, "exec a shell command"}, {"fib", spam_fib, METH_VARARGS, "cal fibonacci number"}, {NULL, NULL, 0, NULL}};
4. 模块初始化函数
PyMODINIT_FUNCinitspam(void){ PyObject *m; m = Py_InitModule("spam", SpamMethods); if (m==NULL) return; SpamError = PyErr_NewException("spam.error", NULL, NULL); Py_INCREF(SpamError); PyModule_AddObject(m, "error", SpamError);}
这样c扩展就写好了,现在是将其编译成动态连接库,python提供了一个很好得工具distutils, 就不需要自己写makefile 手动编译了
5.编写setup.py
from distutils.core import setup, Extensionmodule1 = Extension('spam', sources = ['spammodule.c'])setup (name = 'spam', version = '1.0', description = 'this is a demo package', ext_modules = [module1], author = 'Arthur')
6. python setup.py build #编译
python setup.py install #安装
python setup.py sdist #将源码打包
- 用c扩展python
- 用C/C++扩展Python
- 用C/C++扩展Python
- [原]用C扩展python
- 扩展python 用C语言编写python扩展代码
- 用C语言扩展Python的功能
- 用C语言扩展Python的功能
- 用C语言扩展Python的功能
- 用C语言扩展Python的功能
- 用 C 扩展 Python 和 Zope
- 用C语言扩展Python的功能
- 用C语言扩展Python的功能
- 用C语言扩展Python的功能
- 用C语言扩展Python的功能
- 用C语言扩展Python的功能
- 用C语言扩展Python的功能
- 用C语言扩展python笔记
- 用C语言扩展Python的功能
- Linux 文件系统概述
- 解决Android在listview中checkbox批量操作问题
- highcharts js报表库文件 文档地址
- 帮助文件的作用。
- mysql_install_db无法创建var目录
- 用c扩展python
- Excel条件格式的应用1——添加醒目行
- drupal
- android之学习杂记(一)
- 牛人的server博客
- 创建db2数据库需要注意问题
- 心情相当的不好!
- Adobe平台推广总监Ben Forta:加大HTML5投入 Flex贡献给开源社区
- C#实现WinForm窗口最小化到系统托盘