我正在尝试使用 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 的版本?
最佳答案
这很简单。您需要进行以下更改:
- 将 pybind11 包含目录添加到您的包含(
-I
标志)。 - 将 Python 3 header 添加到您的包含(
-I
标志)。 - 将 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++ 编译器标志、库和/或链接器标志的变量,因此您需要添加 -I
和 python3-config
在那里调用。
关于c++ - 如何使用 PyBind 将 Python 嵌入到 C++ 中,而不是使用 CMake?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47678976/