0

我有一个具有以下结构的示例。

├── CMakeLists.txt
├── ext
│   └── pybind11
└── main.cpp

CMakeLists.txt

cmake_minimum_required(VERSION 3.5)
project(notworking)
add_subdirectory(ext/pybind11)
add_executable(notworking
  main.cpp)
target_link_libraries(notworking PRIVATE python3.6m)
target_link_libraries(notworking PRIVATE pybind11)

主文件

#include <pybind11/pybind11.h>

namespace py = pybind11;

int main() { py::object decimal = py::module::import("decimal"); }

现在在运行时

╰─ ./notworking
[1]    14879 segmentation fault (core dumped)  ./notworking

为了让这个模块在这里正确加载,我缺少什么?我已经搜索了文档,特别是构建系统部分,但结果是空的。

在 C++ 的 pybind11 中使用其他包装器时,我似乎也是这种情况。

4

1 回答 1

5

我有您的示例的修改版本,可以使用本地和本机模块运行。基本程序如下:

安装 python3.6、python3.6-dev 和 CMake(3.10 最新)。我只安装了python3.6(版本3.6.3)

从github下载 pybind11-master并解压。在解压后的文件夹中:

mkdir build
cd build
cmake ..
make check -j 4
sudo make install

使用简单的 main.cpp 和 calc.py 源创建“notworking”项目:

主要.cpp:

#include <pybind11/embed.h> 
namespace py = pybind11;

int main() {
    py::scoped_interpreter guard{};

    py::print("Hello, World!"); 

    py::module decimal = py::module::import("decimal");
    py::module calc = py::module::import("calc");
    py::object result = calc.attr("add")(1, 2);
    int n = result.cast<int>();
    assert(n == 3);
    py::print(n);
}

Calc.py(这必须存在于同一文件夹中:)

def add(i, j):
    return i + j

我的简单 CMakeLists.txt 文件:

cmake_minimum_required(VERSION 3.5)
project(notworking)

find_package(pybind11 REQUIRED) 

add_executable(notworking main.cpp)
target_link_libraries(notworking PRIVATE pybind11::embed)

构建和运行给出了输出:

Hello, World!
3

希望这个对你有帮助。

于 2017-12-13T17:43:11.077 回答