用python脚本写应用比较方便,但有时候由于种种原因需要扩展python(比如给程序提供python接口等)。 之前一直想整理下,今天终于坐下来把这件事情给做了,这里记录下,也方便我以后查阅。
直接调用动态库
1、编写模块动态库文代码
这里以求最大数为示例
代码(callTest1.cpp)如下:
extern "C"
{
int Max(int i1,int i2)
{
return (i1>i2)?i1:i2;
}
}
在bash中执行以下命令:
g++ -fPIC -shared -o libcallTest1.so callTest1.cpp
生成动态库文件libcallTest1.so
2、使用python调用动态库
可以通过ctypes调用动态库文件,具体如下:
#! /usr/bin/env python
from ctypes import *
import os
so1 = CDLL(os.getcwd() + '/libcallTest1.so')
print so1.Max(1,3)
使用boost库扩展python
这种方式可以直接生成python模块,使用import操作直接导入即可。 当然使用这种方式,需要安装boost库,具体操作这里就不说了,不懂的朋友自己查下。
boost官网:http://www.boost.org/
1、模块代码如下:
文件名:boostCallTest1.cpp
文件内容:
int Max(int i1,int i2)
{
return (i1>i2)?i1:i2;
}
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(boostCallTest1)
{
def("Max",Max);
}
2、编写模块编译脚本
文件名: setup.py
文件内容:
#!/usr/bin/env python
from distutils.core import setup
from distutils.extension import Extension
setup(name="PackageName",
ext_modules=[
Extension("boostCallTest1", ["boostCallTest1.cpp"],
libraries = ["boost_python"])
])