C++和Python的混合编程-Boost::python的编译和配置

视频教程: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)
C++和Python的混合编程-Boost::python的编译和配置_第1张图片
  • 在开始菜单的VS菜单项里打开“Developer Command Prompt for VS2015”,进入boost目录
C++和Python的混合编程-Boost::python的编译和配置_第2张图片
  • 运行bootstrap.bat,会在根目录下生产bjam.exe,b2.exe(bjam的升级版),project-config.jam,bootstrap.log四个文件
C++和Python的混合编程-Boost::python的编译和配置_第3张图片
  • 编译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文件夹下,也可以复制出来,放入到统一的地方,方便其他程序调用
C++和Python的混合编程-Boost::python的编译和配置_第4张图片
C++和Python的混合编程-Boost::python的编译和配置_第5张图片

VS工程的配置,编译和基础示例

  • VS2015建立名为Boost_Python_Sample的Win32的dll工程
  • VS2015也可建立一个Win32 Console Applicantion,然后在VS->Project->Properties::Genneral::Configuration Type里改成dll
C++和Python的混合编程-Boost::python的编译和配置_第6张图片
  • 工程设置(Project->Properties->VC++ Directories)
    • Include Diretorise加上Boost根目录
    • Include Diretorise加上Python的include目录
    • Library Diretoties加上boost编译出来的lib目录
    • Library Diretoties加上Python的libs目录
C++和Python的混合编程-Boost::python的编译和配置_第7张图片
C++和Python的混合编程-Boost::python的编译和配置_第8张图片
  • Python_Test_Sample为导出的模块dll,可直接将输出程序的后缀名改成pyd


    C++和Python的混合编程-Boost::python的编译和配置_第9张图片
  • 因为使用的是静态编译的boost::python库,所以在include头文件之前要加上BOOST_PYTHON_STATIC_LIB,因为在boost::python库的config.hpp中规定,如没定义BOOST_PYTHON_STATIC_LIB ,则采用动态编译的库

    C++和Python的混合编程-Boost::python的编译和配置_第10张图片

#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 
#include 

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")
        .def("hello", &StructionData::hello)
        .def("printmsg", &StructionData::printmsg);
}

//Boost_Python_Sample为导出的模块名
//StructionData为类名
//hello和printmsg是成员函数名

导出的模块名需要和生成的pyd文件名相同

  • 将pyd文件拷贝到python的库目录下(python —>lib —>site-packages),或者命令行直接进入pyd所在的目录。
C++和Python的混合编程-Boost::python的编译和配置_第11张图片
  • 命令行进入python,导入并调用pyd的导出模块和函数
C++和Python的混合编程-Boost::python的编译和配置_第12张图片

你可能感兴趣的:(C++和Python的混合编程-Boost::python的编译和配置)