[Python] CMake构建boost python的写法

406 0
Honkers 2026-6-16 23:18:04 来自手机 | 显示全部楼层 |阅读模式

最近需要用到python的胶水功能,即python调用c++,将源文件编译成.so,然后在python中import即可以用到此动态库文件。同时,原始项目是使用cmake构建的,所以也希望用cmake构建boost python。找了好长时间没有合适教程并且出现了一些问题,在这里总结一下,欢迎补充和交流

参考地址:https://stackoverflow.com/questions/52929146/boostpython-and-cmake

hello_ext.cpp

  1. #include <boost/python.hpp>
  2. #include <iostream>
  3. extern "C"
  4. char const* greet()
  5. {
  6. return "hello, world";
  7. }
  8. BOOST_PYTHON_MODULE(libhello_ext)
  9. {
  10. using namespace boost::python;
  11. def("greet", greet);
  12. }
  13. int main(){
  14. std::cout<<greet()<<std::endl;
  15. return 0;
  16. }
复制代码

此文件可以作为一个简单示例,#include 是boostpython编程需要的头文件。这里要注意BOOST_PYTHON_MODULE(libhello_ext)括号中的内容要与生成动态文件库同名(cmake生成的名称前面加上了lib,这里是为了凑名称相同,具体原因没搞清楚)。有了源文件,在Ubuntu系统下可以直接使用Makefile,这里也列举出来。

  1. # location of the Python header files
  2. PYTHON_VERSION = 27
  3. PYTHON_DOT_VERSION = 2.7
  4. PYTHON_INCLUDE = /usr/include/python$(PYTHON_DOT_VERSION)
  5. # location of the Boost Python include files and library
  6. BOOST_INC = /usr/include
  7. BOOST_LIB = /usr/lib/x86_64-linux-gnu/
  8. # compile mesh classes
  9. TARGET = hello_ext
  10. $(TARGET).so: $(TARGET).o
  11. g++ -shared -Wl,--export-dynamic $(TARGET).o -L$(BOOST_LIB) -lboost_python-py$(PYTHON_VERSION) -L/usr/lib/python$(PYTHON_DOT_VERSION)/config-x86_64-linux-gnu -lpython$(PYTHON_DOT_VERSION) -o $(TARGET).so
  12. $(TARGET).o: $(TARGET).cpp
  13. g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).cpp
复制代码

注意复制的时候g++前面是Tab。这里主要说的是Cmake,给出Cmake的代码,cmake每一行的含义可以找教程看一看,我看懂了也会更新的。

  1. cmake_minimum_required(VERSION 3.6)
  2. PROJECT(hello_ext)
  3. # Find Boost
  4. find_package(Boost REQUIRED COMPONENTS python-py27)
  5. set(PYTHON_DOT_VERSION 2.7)
  6. set(PYTHON_INCLUDE /usr/include/python2.7)
  7. set(PYTHON_LIBRARY /usr/lib/python2.7/config-x86_64-linux-gnu)
  8. include_directories(${PYTHON_INCLUDE} ${Boost_INCLUDE_DIRS})
  9. SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -lrt -O3")
  10. SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
  11. SET(LIBNAME hello_ext)
  12. add_library(${LIBNAME} SHARED hello_ext.cpp)
  13. #add_executable(${PROJECT_NAME} hello_ext.cpp)
  14. TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${Boost_LIBRARIES} -lpython2.7 -fPIC)
  15. TARGET_LINK_LIBRARIES(${LIBNAME} ${Boost_LIBRARIES} -lpython2.7 -fPIC -shared)
复制代码

测试结果:

                   

出现问题1:pyconfig.h no such file

可以的解决方法:在make之前

  1. export CPLUS_INCLUDE_PATH=/usr/include/python2.7
复制代码

 

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行