- 论坛徽章:
- 0
|
python的强大不仅表现在其功能上,而且还表现在其扩展能力上。
使用C/C++很容易编写python的模块,扩展python的功能。
同时将性能要求比较高的代码使用C/C++编写,能更好的弥补
脚本语言执行速度慢的缺陷。
1. python的C语言扩展
1.1 TestCLib.c: 提供python的模块接口
#include "Python.h"
#include
#include
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
#include
// ------------------------------------------------------
// Pure C
code
// ------------------------------------------------------
long fac(long n)
{
if ( n
#include
#include "test.h"
// ------------------------------------------------------
// Pure CPP
code
// ------------------------------------------------------
namespace Test{
long CTest::fac(long n)
{
if ( n
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/110228/showart_2148725.html |
|