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
标签:setuptools,extension,setup,py,试用,pybind11,mydemo From: https://www.cnblogs.com/rongfengliang/p/18552984