当前位置: 首页 > news >正文

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 有以下优势:

  1. 更快的编译时间
  2. 更小的二进制体积
  3. 更好的类型转换性能
  4. 更简单的绑定代码

总结

nanobind 是一个高效、现代的 C++/Python 绑定工具,特别适合需要高性能和快速开发的项目。通过上面的示例,你可以开始将你的 C++ 代码暴露给 Python 使用。

相关文章:

  • 如何用命令行判断一个exe是不是c#wpf开发的
  • 金融企业如何借力运维监控强化合规性建设?
  • Linux系列:如何用perf跟踪.NET程序的mmap泄露
  • 点云采集学习个人记录
  • Mkdocs文档引用相对地址的一些问题
  • 从D盘分配空间为C盘扩容?利用工具1+1>2
  • uni-app实现完成任务解锁拼图功能
  • MySQL OCP和Oracle OCP怎么选?
  • POI处理EXCEL
  • 51camera将参加第九届沥青路面论坛暨新技术新成果展示会
  • LeetCode 347 前 K 个高频元素
  • Word如何制作三线表格
  • HDMI布局布线
  • AI大模型基础设施:NVIDIA GPU和AMD MI300系列的区别
  • C++11新特性讲解
  • ACE-Step - 20秒生成4分钟完整歌曲,音乐界的Stable Diffusion,支持50系显卡 本地一键整合包下载
  • 基于RK3568多功能车载定位导航智能信息终端
  • hadoop中的序列化和反序列化(4)
  • Excel表格怎样导出为csv格式
  • 人脸识别技术应用管理办法的影响
  • 宜昌全域高质量发展:机制创新与产业重构的双向突围
  • 习近平结束对俄罗斯国事访问并出席纪念苏联伟大卫国战争胜利80周年庆典回到北京
  • 北京2025年住房发展计划:供应商品住房用地240-300公顷,建设筹集保租房5万套
  • 明星同款撕拉片,为何能炒到三四百一张?
  • 印巴冲突升级,巴基斯坦股市重挫7.29%,创5年来最大单日跌幅
  • Meta正为AI眼镜开发人脸识别功能