我有以下示例程序:
// src/main.cpp
#include <boost/python.hpp>
char const* func()
{
return "String";
}
BOOST_PYTHON_MODULE(bridge)
{
boost::python::def("func", func);
}
使用以下CMakeLists.txt构建时,不会给出编译器错误:
project(bridge)
cmake_minimum_required(VERSION 3.5)
set(PROJECT_SOURCE_DIR ${CMAKE_SOURCE_DIR}/src)
set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/bin)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set(SOURCE_FILES
${PROJECT_SOURCE_DIR}/main.cpp
)
# Include Python
#set(Python_ADDITIONAL_VERSIONS 3.5)
find_package(PythonLibs)
if (${PYTHONLIBS_FOUND})
include_directories(${PYTHON_INCLUDE_DIRS})
link_directories(${PYTHON_LIBRARIES})
endif()
# Include Boost
find_package(Boost 1.61.0 COMPONENTS python REQUIRED)
if (${Boost_FOUND})
include_directories(${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIR})
endif()
# Enable C++ 11
add_compile_options(-std=c++11)
add_compile_options("-lboost_python")
add_library(bridge SHARED ${SOURCE_FILES})
target_link_libraries(bridge ${PYTHON_LIBRARIES})
target_link_libraries(bridge ${Boost_LIBRARIES})
但是,导入共享库(libbridge.so)会出现以下错误:
/bin$ python
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import libbridge
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: ./libbridge.so: undefined symbol: _ZN5boost6python6detail11init_moduleER11PyModuleDefPFvvE
我编译了boost和boost_python没有任何问题,其他的boost库完全正常运行。这有什么不对?
编辑:在另一篇文章中,通过使文件名与输入BOOST_PYTHON_MODULE
的参数相同来给出解决方案。完成这些修改后,import libbridge
:
ImportError: ./libbridge.so: invalid ELF header
导出环境变量$LD_LIBRARY_PATH=$BOOST_ROOT/stage/lib
似乎没有产生任何影响。
答案 0 :(得分:2)
我找到了解决方案。问题是由于Boost内部的Python版本不匹配。我决定在Python 3中编译所有内容,它解决了这个问题。我进行如下:
我将以下行取消注释到user-config.jam
$BOOST_ROOT/tools/build/example/
使用python:3.5:/ usr / bin / python3:/usr/include/python3.5:/ usr / lib;
Boost.Python是使用命令从头开始构建的(在sudo中执行以获得/usr/local
的权限)
$ BOOST_ROOT:./ b2 --with-python --clean $ BOOST_ROOT:./ b2 --with-python --install
我使用
验证了这些库确实是Python 3$BOOST_ROOT : nm -D stage/lib/libboost_python-3.so | grep PyClass_Type
不应该给出输出。如果库是用Python 2编译的,那么U PyClass_Type
就会显示出来。
示例项目中的CMakeLists.txt
文件略有修改:
set(Python_ADDITIONAL_VERSIONS 3.5)//取消注释 find_package(Boost 1.61.0 COMPONENTS python3 REQUIRED)// python3而不是python add_compile_options(“ - lboost_python”)//已删除
现在python3
(不是python
)应该可以链接到已编译的libbridge.so
库。