安装setuptools和pybing11:
pip install pybind11
pip install setuptools
add.cpp
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add(int i, int j)
{
return i + j;
}
PYBIND11_MODULE(myadd, m){
m.def("my_add", &add, py::arg("a"), py::arg("b"), "Add two integers");
}
setup.py
from glob import glob
from pybind11.setup_helpers import Pybind11Extension, build_ext
from setuptools import setup
__version__ = "0.0.1"
ext_modules = [
Pybind11Extension(
"myadd",
sorted(glob("./*.cpp")), # Sort source files for reproducibility
define_macros = [('VERSION_INFO', __version__)],
),
]
setup(
name="myadd",
version=__version__,
author="",
author_email="",
url="",
description="cpp project using pybind11",
long_description="",
ext_modules=ext_modules,
extras_require={"test": "pytest"},
cmdclass={"build_ext": build_ext},
zip_safe=False,
python_requires=">=3.7",
)
test.py
from myadd import my_add
a = 10
b = 10
print(my_add(a,b))
运行:
pip install .