Ubuntu下编写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

相关内容