Pybind11 是一个 C++ 库,它允许你将 C++ 代码暴露给 Python,同时保持类型安全和性能。

安装

你可以使用 pip 来安装 Pybind11:

pip install pybind11

使用

以下是一个简单的例子,展示如何使用 Pybind11:

#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

PYBIND11_MODULE(example, m) {
    m.def("add", &add, "A function which adds two numbers");
}

要编译并运行这个模块,你可以使用以下命令:

c++ -std=c++11 -o example example.cpp -I/usr/include/python3.8 -lpython3.8

运行 Python 代码:

import example

print(example.add(1, 2))

资源

Pybind11 Logo