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:
相关文档:
5、#define宏定义。宏只是简单的文本替换,很容易引起歧义。
#include <stdio.h>
#define CONS(a,b) (int)(a##e##b)
#define STR(s) #s
int main()
{
printf(STR(vck));
printf("\n");
printf("%d\n",CONS(2,3));
return 0; ......
今天无事,在论坛上一直看贴子,很少动手实践,今天试着写了一个读取源程序代码行数的例子:
现在的代码如下,可能还有不完善的地方,以后再改进:
#include <stdio.h>
#define CHARCOUNT 255
#define CON 6 /*单行注释最少的时候*/
int realLength = 0;
/*
* function name: strCount
* function : count ......
C程序是由一组或是变量或是函数的外部对象组成的。 函数是一个自我包含的完成一定相关功能的执行代码段。下面小编和大家分享下C语言中的函数。
1. malloc函数
malloc函数的功能是内存分配函数,其用法为:void *malloc(unsigned size);程序实例如下:
#include <stdio.h>
#i ......
C程序是由一组或是变量或是函数的外部对象组成的。 函数是一个自我包含的完成一定相关功能的执行代码段。下面小编和大家分享下C语言中的函数。
1. parsfnm函数
parsfnm函数的功能是分析文件名,其用法为:char *parsfnm (char *cmdline, struct fcb *fcbptr, ......
c# 4.0新特性一览
终于静下心来仔细听了一遍Anders Hejlsberg(Visual Studio组的TECHNICAL FELLOW,C#的设计者之一)在PDC08上讲的“The Future of C#”(http://channel9.msdn.com/pdc2008/TL16/)。
回顾C#发展的历史,C#1.0完全是模仿Java,并保留了C/C++的一些特性如struct,新学者很容易上手;C#2.0加入 ......