手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Ubuntu下编写python c++ 扩展

[日期:2009-12-21] 来源:farmer1992.phpsix.net  作者:farmer1992 [字体:大 中 小]

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

linux
相关资讯       C++  python  Ubuntu知识 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款