pybind11 setuptools 集成试用

pybind11 支持基于setuptools的构建,以下是一个简单试用

项目代码

  • 结构
├── README.md
├── mydemo
│   ├── __init__.py
│   └── demo.py
├── setup.py
└── src
    └── example.cpp
  • 代码说明

src/example.cpp 是基于pybind11 的c++ 扩展

mydemo/__init__.py 是入口,mydemo/demo.py是一个简单的基于python代码的方法

setup.py 定义

from setuptools import setup, find_packages
from pybind11.setup_helpers import Pybind11Extension, build_ext

# Define the pybind11 extension
ext_modules = [
    Pybind11Extension(
        "mydemo.extension",  # Module path
        ["src/example.cpp"],  # Source file
    ),
]

# Package setup
setup(
    name="mydemo",
    version="0.1.0",
    author="Your Name",
    author_email="your_email@example.com",
    description="A Python package with pybind11 and pure Python code",
    long_description=open("README.md").read(),
    long_description_content_type="text/markdown",
    ext_modules=ext_modules,  # Include the pybind11 extension
    cmdclass={"build_ext": build_ext},
    packages=find_packages(),  # Automatically find pure Python modules
    zip_safe=False,
    python_requires=">=3.7",
)

src/example.cpp

#include <pybind11/pybind11.h>

namespace py = pybind11;

int add(int a, int b) {
    return a + b;
}

PYBIND11_MODULE(extension, m) {
    m.doc() = "A pybind11 example extension module";
    m.def("add", &add, "A function that adds two numbers");
}

mydemo/__init__.py

from .extension import add
from .demo import myadd

__all__ = ['add', 'myadd']

mydemo/demo.py

def myadd(a, b):
    return a + b
  • 构建

注意需要结合版本安装setuptools 以及pybind11 等

python setup.py bdist_wheel

说明

注意c native extension 的命名以及pybind11 注册的模块命名,否则加载会有问题,实际属于python 模块加载的内部机制

参考资料

https://pybind11.readthedocs.io/en/stable/compiling.html#modules-with-setuptools

https://docs.python.org/3/c-api/index.html

https://setuptools.pypa.io/en/latest/setuptools.html

https://medium.com/swlh/make-python-hundreds-of-times-faster-with-a-c-extension-9d0a5180063e

posted on   荣锋亮  阅读(8)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2024-01-23 dbt-language-server fivetran 提供的dbt 语言工具
2023-01-23 coredns mysql 扩展使用+readyset 试用
2023-01-23 caddyserver nginx adaper 简单说明
2022-01-23 smithy aws 开源的方便开发语言无关服务SDK的idl
2022-01-23 Fluid Framework微软开源的构建实时分布式协作web 应用的框架
2022-01-23 modelmapper 简单智能的对象映射工具
2022-01-23 基于commons-discovery 开发简单的插件化java系统

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示