3

我正在尝试使用 PyBind 在 C++ 中嵌入一些 Python 代码。大多数文档都是关于使用 C++ 扩展 Python,但我对嵌入感兴趣:

http://pybind11.readthedocs.io/en/stable/advanced/embedding.html上有一个使用 cmake 的简单示例。但是对于我的项目,我必须扩展一个 makefile。

是否可以更改此示例

cmake_minimum_required(VERSION 3.0)
project(example)

find_package(pybind11 REQUIRED)  # or `add_subdirectory(pybind11)`

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

使用这个 c++ 文件

#include <pybind11/embed.h> // everything needed for embedding
namespace py = pybind11;

int main() {
    py::scoped_interpreter guard{}; // start the interpreter and keep it alive

    py::print("Hello, World!"); // use the Python API
}

到带有makefile的版本?

4

1 回答 1

2

这很简单。您需要进行以下更改:

  1. 将 pybind11 包含目录添加到您的包含(-I标志)。
  2. 将 Python 3 标头添加到您的包含(-I标志)中。
  3. 将 Python 3 库添加到您的库(-L标志)。

Python 的python3-config程序是执行#2 和#3 的最佳方式。

例如,如果您有一个看起来像这样的 makefile:

%.o: %.cc
    $(CXX) -o $@ -c $^

main: main.o
    $(CXX) -o $@ $^

然后你需要像这样改变它:

%.o: %.cc
    $(CXX) -o $@ -c $^ -Ipath/to/pybind11-2.2.3/include $(shell python3-config --includes)

main: main.o
    $(CXX) -o $@ $^ $(shell python3-config --libs)

在实践中,您的 Makefile 可能具有提供包含路径、C++ 编译器标志、库和/或链接器标志的变量,因此您将在此处添加-Ipython3-config调用。

于 2018-06-03T23:25:13.557 回答