通过Setuptools和pybind11丝滑实现python调用C++

安装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 .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值