如何在 Ubuntu 上导入使用 pybind11 创建的模块

Air*_*d20 4 c++ python linux cmake pybind11

我正在尝试设置一个 CMake 项目,在 Ubuntu 上使用 pybind11 为其 C++ 函数创建 python 绑定。

目录结构为:

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

文件CMakeLists.txt

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})
Run Code Online (Sandbox Code Playgroud)

arithmetic.cpython-36m-x86_64-linux-gnu.so存储库已成功构建并生成文件。如何将此共享对象文件导入到 python 中?

pybind11 文档中的文档有这一行

$ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
Run Code Online (Sandbox Code Playgroud)

但我想使用 CMake 进行构建,并且我也不想每次运行 python 来使用此模块时都必须指定额外的包含目录。

我如何像普通的 python 模块一样将此共享对象文件导入到 python 中?

我使用的是 Ubuntu 16.04。

sup*_*per 6

如果打开终端,请转到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
Run Code Online (Sandbox Code Playgroud)

通过这种方法,您可以使用相对路径和绝对路径。