博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Boost.Python入门实例
阅读量:4548 次
发布时间:2019-06-08

本文共 1854 字,大约阅读时间需要 6 分钟。

环境

  • gcc
  • boost brew install boost
  • boost-python brew install boost-python

代码

  • Rectangle.cpp
#include 
#include
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_;};
  • Rectangle2py.cpp
#include 
#include "Rectangle.cpp"using namespace boost::python;BOOST_PYTHON_MODULE(rectangle) //python模块{ class_
("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) ;}
  • makefile
PY_INCLUDE = /path/to/python/include/python2.7PY_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_pythonrectangle.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来确定库的名称

转载于:https://www.cnblogs.com/Juworchey/p/8191998.html

你可能感兴趣的文章
MySQL常用命令操作
查看>>
Ocelot 配置初始
查看>>
Git 操作常用命令
查看>>
JavaScript显示时间
查看>>
mysql可视化管理工具
查看>>
sqlserver的rownum
查看>>
《敏捷个人》周刊 第11期 (可下载)
查看>>
蓝桥杯 C语言 入门训练 序列求和
查看>>
总结---JavaScript函数基础总结
查看>>
WebSocket 浅析
查看>>
Android学习之SQLite基础
查看>>
「日常训练」 Fire!(UVA-11624)
查看>>
谭宝,浅浅谈
查看>>
Alpha 冲刺 (3/10)
查看>>
评论抓取:Python爬取微信在APPStore上的评论内容及星级
查看>>
汇编 指令lodsb,lodsw,lodsd
查看>>
[HAOI2007] 上升序列
查看>>
Java笔记第二篇 Java环境初知道
查看>>
利用POI遍历出层级结构的excel表格
查看>>
js 数据的常用操作
查看>>