BoostPython 和 CMake

El_*_*oco 6 c++ python cmake boost-python

我已经成功地按照这个例子来了解如何连接 C++ 和 python。当我使用给定的Makefile. 当我尝试使用cmake它时,效果不佳。

C++代码:

#include <boost/python.hpp>
#include <iostream>
extern "C"
char const* greet()
{
   return "hello, world";
}

BOOST_PYTHON_MODULE(hello_ext)
{
    using namespace boost::python;
    def("greet", greet);
}

int main(){
    std::cout<<greet()<<std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

生成文件:

# location of the Python header files
PYTHON_VERSION = 27
PYTHON_DOT_VERSION = 2.7
PYTHON_INCLUDE = /usr/include/python$(PYTHON_DOT_VERSION)
# location of the Boost Python include files and library
BOOST_INC = /usr/include
BOOST_LIB = /usr/lib/x86_64-linux-gnu/
# compile mesh classes
TARGET = hello_ext
$(TARGET).so: $(TARGET).o
    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
$(TARGET).o: $(TARGET).cpp
    g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).cpp
Run Code Online (Sandbox Code Playgroud)

当我编译这个时,我得到一个.so可以包含在脚本中的文件

import sys
sys.path.append('/home/myname/Code/Trunk/TestBoostPython/build/')
import libhello_ext_lib as hello_ext

print(hello_ext.greet())
Run Code Online (Sandbox Code Playgroud)

我真的很想使用cmake而不是手动编写Makefile所以我写了这个:

cmake_minimum_required(VERSION 3.6)
PROJECT(hello_ext)

# Find Boost
find_package(Boost REQUIRED COMPONENTS python-py27)

set(PYTHON_DOT_VERSION 2.7)
set(PYTHON_INCLUDE /usr/include/python2.7)
set(PYTHON_LIBRARY /usr/lib/python2.7/config-x86_64-linux-gnu)

include_directories(${PYTHON_INCLUDE} ${Boost_INCLUDE_DIRS})

SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -lrt -O3")

SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
SET(LIBNAME hello_ext_lib)

add_library(${LIBNAME} SHARED src/hello_ext.cpp)
add_executable(${PROJECT_NAME} src/hello_ext.cpp)

TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${Boost_LIBRARIES} -lpython2.7 -fPIC)
TARGET_LINK_LIBRARIES(${LIBNAME} ${Boost_LIBRARIES} -lpython2.7 -fPIC -shared)
Run Code Online (Sandbox Code Playgroud)

在这里,我目前Python-paths手动输入,但我也尝试使用fin_package(PythonLibs)但没有成功。

当我在../bin/. 但是,当我运行 python 脚本时,我总是得到:

ImportError: dynamic module does not define init function (initlibhello_ext_lib)
Run Code Online (Sandbox Code Playgroud)

我发现表明如果libexecutable具有不同的名称,就会发生这种情况。确实如此,但我如何获得.so正确的名称?

我也尝试不编译可执行文件而只编译库。这也不起作用。

Ghp*_*pst 3

BOOST_PYTHON_MODULE(hello_ext)创建一个初始化函数“inithello_ext”,它应该对应于一个模块“hello_ext”。但您正在尝试导入“libhello_ext_lib”。

为模块指定与文件名相同的名称。例如BOOST_PYTHON_MODULE(libhello_ext_lib)