Python 的C语言扩展
操作系统:linux debian 4.0, python版本2.5
s1:安装python2.5-dev。因为Python.h是在dev包中才有。
test@debian:~/test_python_c$ aptitude search python2.5-dev
p python2.5-dev - Header files and a static library for Python.
test@debian:~/test_python_c$ sudo aptitude install python2.5-dev
...
test@debian:~/test_python_c$ aptitude search python2.5-dev
i python2.5-dev - Header files and a static library for Python.
s2:准备测试文件——C语言函数
//filename:example.c
int fact(int n)
{
if(n<=1)
return 1;
else
return n*fact(n-1);
}
s3: 编写封装接口
//filename: wrap.c
#include <Python.h>
PyObject* wrap_fact(PyObject* self, PyObject* args)
{
int n, result;
if (! PyArg_ParseTuple(args, "i:fact", &n))
return NULL;
result = fact(n);
return Py_BuildValue("i", result);
}
static PyMethodDef exampleMethods[] =
{
{"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
{NULL, NULL}
};
void initexample()
{
PyObject* m;
m = Py_InitModule("example", exampleMethods);
}
s4:编译连接
gcc -fpic -c -I /usr/include/python2.5 -I /usr/lib/python2.5/config example.c wrap.c
gcc -shared -o example.so example.o wrap.o
test@debian:~/test_python_c$ ls
example.c example.o example.so wrap.c wrap.o
s5:测试example扩展模块
test@debian:~/test_python_c$ python
Python 2.5 (release25-maint, Jul 20 2008, 20:47:25)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> dir(example)
['__doc__', '__file__', '__name__', 'fact']
>>> example.fact(5)
120
>>> example.fact(16)
2004189184
>>> example.fact(17)
-288522240
说明fact(17)的时候溢出了。
操作系统:windowsXP, python版本2.5
#TODO:
相关文档:
第一种理解
比如说你用C++开发了一个DLL库,为了能够让C语言也能够调用你的DLL输出(Export)的函数,你需要用extern "C"来强制编译器不要修改你的
函数名。
通常,在C语言的头文件中经常可以看到类似下面这种形式的代码:
#ifdef __cplusplus
extern "C" {
#endif
/**** some declaration or so *****/
#ifde ......
神乎其技,惟C程序,功到自成,十大建议!
1、汝应频繁催动lint工具,据其语法声明修习内力,此事皆因lint之思虑决断实远在君上。
2、不可依随NULL指针,如若不然,混沌痴颠必俟君于彼岸。
3、纵有天赋大智慧,知晓其事无碍,汝亦当尽数强制挪移函数参数为原型所期之数据类型,以免一 ......
C程序是由一组或是变量或是函数的外部对象组成的。 函数是一个自我包含的完成一定相关功能的执行代码段。下面小编和大家分享下C语言中的函数。
1. normvideo函数
malloc函数的功能是选择正常亮度字符,其用法为:void normvideo(void);程序实例如下:
#include < ......
用函数access,头文件是io.h,原型:
int access(const char *filename, int amode);
amode参数为0时表示检查文件的存在性,如果文件存在,返回0,不存在,返回-1。
这个函数还可以检查其它文件属性:
06 &nbs ......
#define NULL 0
#define LEN 10
#define OK printf("\n此组数据合格。\n")
#define NO printf("\n此组数据不合格!\n")
#define CN printf("\n%30c 伟成工作室荣誉出品 %c\n",17,16)
#include "stdlib.h"
#include "math.h"
static float min,ave;
float *zwfloat(void ......