python的C、c++扩展
python的C、c++扩展
http://blog.chinaunix.net/u3/110228/showart_2148725.html
python的强大不仅表现在其功能上,而且还表现在其扩展能力上。
使用C/C++很容易编写python的模块,扩展python的功能。
同时将性能要求比较高的代码使用C/C++编写,能更好的弥补
脚本语言执行速度慢的缺陷。
1. python的C语言扩展
1.1 TestCLib.c: 提供python的模块接口
#include "Python.h"
#include <stdlib.h>
#include <stdio.h>
long fac(long);
// ------------------------------------------------------
// Make C code usable in Python
// ------------------------------------------------------
PyObject* TestCLib_fac(PyObject * self, PyObject *args)
{
long num;
if ( ! PyArg_ParseTuple(args,"l",&num)){
return NULL;
}
return (PyObject*)Py_BuildValue("l",fac(num));
}
static PyMethodDef TestCLibMethods[] = {
{"fac",TestCLib_fac,METH_VARARGS},
{NULL,NULL}
};
void initTestCLib()
{
Py_InitModule("TestCLib",TestCLibMethods);
}
1.2 test.c: 具体的C语言实现
#include <stdlib.h>
#include <stdio.h>
// ------------------------------------------------------
// Pure C code
// ------------------------------------------------------
long fac(long n)
{
if ( n < 0){
return fac(-n);
} else if ( n < 2 ){
return 1;
} else {
return n * fac(n-1);
}
}
1.3 test.py: 测试脚本
#!/usr/bin/env python
import TestCLib as TestLib
for i in range(10,20) :
f1 = TestLib.fac(i)
print "%d! = %d"%(i,f1)
1.4 编译与运行
编译命令:
gcc -fPIC -shared -o TestCLib.so TestCLib.c test.c -I /usr/local/python/include/python2.6/
将生成的动态链接库 T
相关文档:
问题源于论坛的一道题目:
http://topic.csdn.net/u/20100216/21/ec98464e-a47e-4263-bb1c-a001e130ba87.html
下面是问题:
设int arr[]={6,7,8,9,10};
int *ptr=arr;
*(ptr++)+=123;
printf("%d,%d",*ptr,*(++ptr));
答案为什么是:8,8
问题的焦点也落在printf执行的问题上,到底先执行谁,后执行谁, 还有部分 ......
Windows C 程序设计入门与提高
http://download.chinaitlab.com/program/files/13246.html
单片机C语言入门
http://download.chinaitlab.com/program/files/12907.html
C++ 入门基础教程
http://download.chinaitlab.com/program/files/7617.html
C语言常用算法源代码
http://download.chinaitlab.com/program/files ......
一个控制台下的数字表达式求值程序 (c/c++)
源代码见下:
#include <stdio.h>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <stack>
using namespace std;
//设置运算符优先级的算法
int Priority(const string opera) // 运算符 ......
前几天,小许给我一份JavaQQ的源代码,用vim打开一看,发现里面的中文都是乱码。不用说,又是可恶的编码问题,在window下的文本文件通常使用GBK或GB18030编码,而在Linux下utf-8编码则大行其道。打开——另存为肯定不是上策,上网找编码批量转换工具也不是咱勤劳勇敢的程序员的作风。自已动手 ......