C/C++ Python绑定工具: nanobind 使用指南与示例
nanobind 使用指南与示例
nanobind 是一个用于将 C++ 代码绑定到 Python 的轻量级库,它比传统的 pybind11 更高效且编译更快。下面我将介绍如何使用 nanobind 并给出几个示例。
安装 nanobind
首先需要安装 nanobind,可以通过 pip 安装:
pip install nanobind
或者从源码安装:
git clone https://github.com/wjakob/nanobind
cd nanobind
pip install .
基本示例
1. 简单的函数绑定
创建一个 example.cpp
文件:
#include <nanobind/nanobind.h>namespace nb = nanobind;int add(int a, int b) {return a + b;
}NB_MODULE(example, m) {m.def("add", &add, "A function that adds two numbers");
}
编译并安装:
c++ -O3 -Wall -shared -std=c++17 -fPIC $(python3 -m nanobind --includes) example.cpp -o example$(python3-config --extension-suffix)
然后在 Python 中使用:
import example
print(example.add(3, 4)) # 输出 7
2. 类绑定
#include <nanobind/nanobind.h>
#include <string>namespace nb = nanobind;class Pet {
public:Pet(const std::string &name) : name(name) {}void setName(const std::string &name_) { name = name_; }const std::string &getName() const { return name; }private:std::string name;
};NB_MODULE(example, m) {nb::class_<Pet>(m, "Pet").def(nb::init<const std::string &>()).def("setName", &Pet::setName).def("getName", &Pet::getName);
}
Python 中使用:
from example import Pet
p = Pet("Molly")
print(p.getName()) # 输出 "Molly"
p.setName("Charly")
print(p.getName()) # 输出 "Charly"
3. 绑定 NumPy 数组
nanobind 提供了对 NumPy 数组的良好支持:
#include <nanobind/nanobind.h>
#include <nanobind/ndarray.h>namespace nb = nanobind;double sum(nb::ndarray<double> array) {double result = 0;for (size_t i = 0; i < array.size(); ++i) {result += array(i);}return result;
}NB_MODULE(example, m) {m.def("sum", &sum);
}
Python 中使用:
import numpy as np
from example import sumarr = np.array([1.0, 2.0, 3.0])
print(sum(arr)) # 输出 6.0
高级特性
4. 绑定 STL 容器
#include <nanobind/nanobind.h>
#include <nanobind/stl/vector.h>
#include <nanobind/stl/string.h>namespace nb = nanobind;std::vector<std::string> process(const std::vector<std::string> &input) {std::vector<std::string> output;for (const auto &s : input) {output.push_back(s + " processed");}return output;
}NB_MODULE(example, m) {m.def("process", &process);
}
Python 中使用:
from example import process
result = process(["a", "b", "c"])
print(result) # 输出 ['a processed', 'b processed', 'c processed']
5. 绑定枚举类型
#include <nanobind/nanobind.h>namespace nb = nanobind;enum class Color { Red = 1, Green = 2, Blue = 3 };NB_MODULE(example, m) {nb::enum_<Color>(m, "Color").value("Red", Color::Red).value("Green", Color::Green).value("Blue", Color::Blue);
}
Python 中使用:
from example import Color
print(Color.Red) # 输出 <Color.Red: 1>
构建系统集成
对于更复杂的项目,可以使用 CMake 来构建:
cmake_minimum_required(VERSION 3.15)
project(example)find_package(nanobind CONFIG REQUIRED)nanobind_add_module(example example.cpp)
性能优势
nanobind 相比 pybind11 有以下优势:
- 更快的编译时间
- 更小的二进制体积
- 更好的类型转换性能
- 更简单的绑定代码
总结
nanobind 是一个高效、现代的 C++/Python 绑定工具,特别适合需要高性能和快速开发的项目。通过上面的示例,你可以开始将你的 C++ 代码暴露给 Python 使用。