视频教程:boost::python库的编译和使用的基本方法
- boost::python用于将C++的函数和对象导出,方便python调用对象和方法,用来实现C++和Python的混合编程。
编译boost::python库
- 下载boost源码,解压到想放到的位置,例如: E:\Learning\Boost\boost_1_69_0
- 编译boost的lib库
- 查看VS的版本,打开任意工程:VS->Project->Properties::Genneral::Plateform Toolset(VS2015为v140)

- 在开始菜单的VS菜单项里打开“Developer Command Prompt for VS2015”,进入boost目录

- 运行bootstrap.bat,会在根目录下生产bjam.exe,b2.exe(bjam的升级版),project-config.jam,bootstrap.log四个文件

- 编译boost::python库(VS2015)
//boost::python lib
bjam toolset=msvc-14.0 --with-python threading=multi link=static address-model=64
//--with-python 里面的python需要是python3版本,要求系统能找到你的python,直接在cmd里面输入python能弹出python3说明没有问题
- 生成的lib在boost的stage文件夹下,也可以复制出来,放入到统一的地方,方便其他程序调用


VS工程的配置,编译和基础示例
- VS2015建立名为Boost_Python_Sample的Win32的dll工程
- VS2015也可建立一个Win32 Console Applicantion,然后在VS->Project->Properties::Genneral::Configuration Type里改成dll

- 工程设置(Project->Properties->VC++ Directories)
- Include Diretorise加上Boost根目录
- Include Diretorise加上Python的include目录
- Library Diretoties加上boost编译出来的lib目录
- Library Diretoties加上Python的libs目录


-
Python_Test_Sample为导出的模块dll,可直接将输出程序的后缀名改成pyd
-
因为使用的是静态编译的boost::python库,所以在include头文件之前要加上BOOST_PYTHON_STATIC_LIB,因为在boost::python库的config.hpp中规定,如没定义BOOST_PYTHON_STATIC_LIB ,则采用动态编译的库
#ifdef BOOST_PYTHON_STATIC_LIB
# define BOOST_PYTHON_STATIC_LINK
# elif !defined(BOOST_PYTHON_DYNAMIC_LIB)
# define BOOST_PYTHON_DYNAMIC_LIB
#endif
- 示例代码
#define BOOST_PYTHON_STATIC_LIB
#include <boost/python.hpp>
#include <iostream>
struct StructionData
{
void hello()
{
std::cout << "hello, this is boost::python sample!" << std::endl;
}
void printmsg()
{
std::cout << "print message done!" << std::endl;
}
};
BOOST_PYTHON_MODULE(Boost_Python_Sample)
{
//struct
boost::python::class_<StructionData>("StructionData")
.def("hello", &StructionData::hello)
.def("printmsg", &StructionData::printmsg);
}
//Boost_Python_Sample为导出的模块名
//StructionData为类名
//hello和printmsg是成员函数名
导出的模块名需要和生成的pyd文件名相同
- 将pyd文件拷贝到python的库目录下(python —>lib —>site-packages),或者命令行直接进入pyd所在的目录。

- 命令行进入python,导入并调用pyd的导出模块和函数

网友评论