# Python 和 C++ 混合编程可以通过多种方式实现,其中一种常见的方法是使用 `pybind11` 库。下面是一个简单的示例代码,展示如何将 C++ 代码与 Python 代码结合。
# 首先,确保你已经安装了 pybind11:
# pip install pybind11
# 创建一个 C++ 文件 (example.cpp)
"""
#include <pybind11/pybind11.h>
int add(int i, int j) {
return i + j;
}
namespace py = pybind11;
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example plugin"; // optional module docstring
m.def("add", &add, "A function which adds two numbers");
}
"""
# 然后创建一个 setup.py 文件来编译这个 C++ 文件
"""
from setuptools import setup, Extension
import pybind11
ext_modules = [
Extension(
'example',
['example.cpp'],
include_dirs=[pybind11.get_include()],
language='c++'
),
]
setup(
name='example',
ext_modules=ext_modules,
python_requires='>=3.6',
)
"""
# 编译扩展模块
# python setup.py build_ext --inplace
# 最后,在 Python 中导入并使用该模块
import example
result = example.add(1, 2)
print(f"The result of adding 1 and 2 is: {result}")
C++ 文件 (example.cpp
):
add
,它接受两个整数参数并返回它们的和。pybind11
库将这个函数绑定到 Python 模块中。Setup 文件 (setup.py
):
setuptools
和 pybind11
来编译 C++ 代码,并生成一个可以被 Python 导入的扩展模块。Python 文件:
add
函数。通过这种方式,你可以轻松地在 Python 中调用 C++ 编写的高性能代码。
下一篇:0基础学python
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站