环境
- gcc
- boost
brew install boost
- boost-python
brew install boost-python
代码
#include <iostream>
#include <string>
using namespace std;
class Rectangle
{
public:
void setWidth(int width)
{
width_ = width;
}
int getWidth()
{
return width_;
}
void setHeight(int height)
{
height_ = height;
}
int getHeight()
{
return height_;
}
int getArea()
{
return width_ * height_;
}
private:
int width_;
int height_;
};
#include <boost/python.hpp>
#include "Rectangle.cpp"
using namespace boost::python;
BOOST_PYTHON_MODULE(rectangle) //python模块
{
class_<Rectangle>("Rectangle")
.def("setWidth",&Rectangle::setWidth)
.def("setHeight",&Rectangle::setHeight)
.def("getWidth",&Rectangle::getWidth)
.def("getHeight",&Rectangle::getHeight)
.def("getArea", &Rectangle::getArea)
.add_property("width",&Rectangle::getWidth,&Rectangle::setWidth)
.add_property("height",&Rectangle::getHeight,&Rectangle::setHeight)
;
}
PY_INCLUDE = /path/to/python/include/python2.7
PY_LIB = /path/to/python/lib/
rectangle.so:rectangle.o rectangle2py.o
g++ rectangle2py.o -o rectangle.so -shared -fPIC -I$(PY_INCLUDE) -L$(PY_LIB) -lpython2.7 -lboost_python
rectangle.o:
g++ -c Rectangle.cpp -o rectangle.o
rectangle2py.o: rectangle.o
g++ -c Rectangle2py.cpp -o rectangle2py.o -fPIC -I$(PY_INCLUDE)
clean:
rm -rf rectangle.o rectangle2py.o
注意事项
- make文件中命令必须以TAB符号开头
- 编译和运行所用的python头文件(Python.h)和python库(libpython2.7.dylib)版本必须一致
- -shared 该选项指定生成动态连接库
- -fPIC 表示编译为位置独立(地址无关)的代码,不用此选项的话,编译后的代码是位置相关的,所以动态载入时,是通过代码拷贝的方式来满足不同进程的需要,而不能达到真正代码段共享的目的
- -L 指定链接库的路径
- -I 头文件搜索路径
- -lxxxx 指定链接库的名称为xxxx,编译器查找动态连接库时有隐含的命名规则,即在给出的名字前面加上lib,后面加上.so来确定库的名称