pybind11 是一个轻量级的库,用于将 C++ 代码绑定到 Python。它支持现代 C++11 标准,生成的绑定代码非常高效。
安装:
pip install pybind11
编写c++代码
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add(int a, int b) {
return a + b;
}
PYBIND11_MODULE(testpy, m) {
m.def("add", &add, "A function that adds two numbers");
}
编写CMakeLists.txt
cmake_minimum_required(VERSION 3.4)
project(your_module_name)
# 找到 pybind11 (D:/Program Files/python3/Lib/site-packages/pybind11 替换成环境下的实际pybind11包路径)
set(pybind11_DIR "D:/Program Files/python3/Lib/site-packages/pybind11/share/cmake/pybind11")
find_package(pybind11 REQUIRED)
# 设置 Python 库和头文件路径 (D:/Program Files/python3 替换成环境下的实际Python安装路径)
set(PYTHON_LIBRARY "D:/Program Files/python3/lib")
set(PYTHON_INCLUDE_DIR "D:/Program Files/python3/include")
# 添加模块
pybind11_add_module(your_module_name *.cpp)
# 设置输出目录和文件名
set_target_properties(your_module_name PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/python_modules
SUFFIX ".pyd"
OUTPUT_NAME "your_module_name"
)
if(WIN32)
target_link_libraries(your_module_name PRIVATE pybind11::module)
endif()
项目结构
project/
├── CMakeLists.txt
├── test.cpp
生成Python module
mkdir build
cd build
cmake ..
make
# 没有装make执行下面命令
# cmake --build . --config Release
把生成的pyd文件拷贝到Python安装包的路径下,即python3/Lib/site-packages/testpy下。
在Python中使用
import sys
sys.path.append('D:/Program Files/python3/Lib/site-packages/testpy')
import testpy
result = testpy.add(3, 4)
print(result) # 输出:7
sys.path.append 把拷贝的路径添加到系统路径。

707

被折叠的 条评论
为什么被折叠?



