编写python c++ 扩展 (ubuntu下)

python 的c++扩展编写 比 php简单很多

phpize 也不是很好用的一个东西

编写一个 python mod hello world

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "Python.h"

PyObject* hello(PyObject* self, PyObject* args){
    const char * str;
   
    if (! PyArg_ParseTuple(args, "s", &str))
        return NULL;

   
    return Py_BuildValue("s",str);
}



static PyMethodDef helloMethods[] =
{
    {"hello", hello, METH_VARARGS, "hello comments"},
    {NULL, NULL, 0, NULL}

};

PyMODINIT_FUNC inithello(void){
    Py_InitModule("hello", helloMethods);
}

一个Python mod 因该有几个部分
1 扩展函数 hello
PyObject* hello(PyObject* self, PyObject* args){
只能是这样的结构
PyArg_ParseTuple 处理参数

2 函数列表 helloMethods
static PyMethodDef helloMethods

3 初始化函数 inithello
init函数名

编译
在 ubuntu 下需要安装python-dev
sudo apt-get install python-dev

yum服务器上应该是
python-devel

1
2
3
4
5
6
7
8
9
10
all: hello.so

hello.so: hello.o
    g++ -shared hello.o -o hello.so

hello.o: hello.cpp
    g++ -fPIC -c -I /usr/include/python2.6/ -o hello.o hello.cpp

clean:
    rm -f hello.o hello.so

使用
写一个 test.py

1
2
3
4
5
#!/usr/bin/env python

import hello

print hello.hello('world')

python 运行时候 会加载当前目录的.so

Posted in 未分类. Tags: , . 评论暂缺 »

python hello

自 php以来 新征服的语言就是 lua了
不过感觉这个东西不怎么吃香
不知道什么原因

大家都在退 python我也投降了
第一个 python 程序是声称 一个 5万条mysql语句的脚本
速度真快
不知道是 python 快还是神气的 linux快

其实能适应 命令行的生活 linux是一个很好的东西
ubuntu 还有点傻 不过我这样的人已经不错了

打破 linux 使用时间记录了 坚持 并等待胜利

Posted in 未分类. Tags: . 评论暂缺 »