用c扩展python代码示例,扩展python示例,搞了一晚上终于做了一个d
用c扩展python代码示例,扩展python示例,搞了一晚上终于做了一个d
搞了一晚上终于做了一个demo,也会用distutils做一个包了,不过现在太晚了,先睡觉,明天好好做下笔记;
写一个简单得python c扩展一共就那么几步,
一. 编写c函数
int math_fib(int n){ if (n<=2) return 1; return math_fib(n-1) + math_fib(n-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); }
三. 模块函数数组
static PyMethodDef SpamMethods[] = { {"system", spam_system, METH_VARARGS, "exec a shell command"}, {"fib", spam_fib, METH_VARARGS, "cal fibonacci number"}, {NULL, NULL, 0, NULL} };
四. 模块初始化函数
PyMODINIT_FUNC initspam(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 手动编译了
五. 编写setup.py
from distutils.core import setup, Extension module1 = Extension('spam', sources = ['spammodule.c']) setup (name = 'spam', version = '1.0', description = 'this is a demo package', ext_modules = [module1], author = 'Arthur')
六. 编译安装
python setup.py build #编译python setup.py install #安装python setup.py sdist #将源码打包
相关内容
- python守护进程例子,python守护进程,来自《python co
- python多线程死锁检测代码,python多线程代码,在多线程程
- python调用grep返回结果,python调用grep返回,下面的函数封
- python记录线程的存活时间,python线程存活,对于长期运行
- python实现逆波兰计算表达式,python波兰表达式,逆波兰表
- python实现封闭类(禁止继承),python封闭,python没有se
- python里的列表list使用范例代码,python范例,#list#新建列
- python winreg 示例,pythonwinreg,下面是关于_winreg
- python连接sql server数据库,pythonsql,首先,到http://p
- Basic synchronization decorator,,下面代码是对python
评论关闭