3

I am trying to setup a CMake project that creates python bindings for its c++ functions using pybind11 on Ubuntu.

The directory structure is:

pybind_test
    arithmetic.cpp
    arithmetic.h
    bindings.h
    CMakeLists.txt
    main.cpp
    pybind11 (github repo clone)
        Repo contents (https://github.com/pybind/pybind11)

The CMakeLists.txt file:

cmake_minimum_required(VERSION 3.10)
project(pybind_test)

set(CMAKE_CXX_STANDARD 17)

find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
include_directories(pybind11/include/pybind11)

add_executable(pybind_test main.cpp arithmetic.cpp)

add_subdirectory(pybind11)
pybind11_add_module(arithmetic arithmetic.cpp)

target_link_libraries(pybind_test ${PYTHON_LIBRARIES})

The repository builds successfully and the file arithmetic.cpython-36m-x86_64-linux-gnu.so is produced. How do I import this shared object file into python?

The documentation in the pybind11 docs has this line

$ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`

but I want to build using CMake and I also don't want to have to specify extra include directories every time I run python to use this module.

How would I import this shared object file into python like a normal python module?

I am using Ubuntu 16.04.

4

2 回答 2

4

如果您打开终端,请转到所在目录arithmetic.cpython-36m-x86_64-linux-gnu.so并运行,python然后import arithmetic该模块将像任何其他模块一样被导入。

另一种选择是使用以下方法

import sys

sys.path.insert(0, 'path/to/directory/where/so-file/is')
import arithmetic

使用此方法,您可以使用相对路径和绝对路径。

于 2018-06-04T20:35:12.013 回答
1

除了@super 提供的在 Python 脚本中设置路径的解决方案外,您还有两个通用解决方案。

设置 PYTHONPATH

Linux(和 macOS)中一个名为PYTHONPATH. 如果您在调用 Python 之前添加包含您的路径*.soPYTHONPATHPython 将能够找到您的库。

去做这个:

export PYTHONPATH="/path/that/contains/your/so":"${PYTHONPATH}"

要为每个会话“自动”应用此行,您可以将此行添加到~/.bash_profileor ~/.bashrc(参见相同的参考)。在这种情况下,Python 将始终能够找到您的库。

将您复制到 Python 路径中已有的路径

您还可以“安装”该库。通常的方法是创建一个setup.py文件。如果设置正确,您可以使用构建和安装库

python setup.py build
python setup.py install

(Python 会知道将您的库放在哪里。您可以使用诸如--user使用您的主文件夹之类的选项来“自定义”一点,但这似乎对您来说并不特别感兴趣。)

问题仍然存在:如何写setup.py?对于您的情况,您实际上可以调用 CMake。事实上,有一个例子可以做到这一点:pybind/cmake_example。您基本上可以从那里复制粘贴。

于 2018-06-05T13:46:40.500 回答