c++打包pyd文件给Python使用调用函数
C语言源码:
simplemath.cpp代码:
//
// Created by ASFOR on 2025/9/11.
//
#include <pybind11/pybind11.h>namespace py = pybind11;// 一个简单的加法函数
int add(int a, int b) {return a + b;
}// 一个简单的乘法函数
int multiply(int a, int b) {return a * b;
}// 定义 Python 模块
PYBIND11_MODULE(simplemath, m) {m.doc() = "A simple math module written in C++";m.def("add", &add, "Add two numbers");m.def("multiply", &multiply, "Multiply two numbers");
}
CMakeLists.txt代码如下:
cmake_minimum_required(VERSION 3.28)
project(simplemath)set(CMAKE_CXX_STANDARD 17)# pybind11 include 路径
include_directories("E:/Users/29165/AppData/Roaming/Python/Python313/site-packages/pybind11/include")# Python include 和 libs
include_directories("D:/software/Python/Python313/include")
link_directories("D:/software/Python/Python313/libs")# 编译成 Python 扩展模块
add_library(simplemath MODULE simplemath/simplemath.cpp)# Windows 下生成 .pyd 而不是 .dll
set_target_properties(simplemath PROPERTIESPREFIX ""SUFFIX ".pyd"
)# 链接 Python 库
target_link_libraries(simplemath python313)
pyproject.toml代码如下:
[build-system]
requires = ["setuptools", "wheel", "pybind11>=2.6.0"]
build-backend = "setuptools.build_meta"
setup.py代码如下:
from setuptools import setup, Extension
import pybind11ext_modules = [Extension("simplemath", # Python 导入模块名["simplemath/simplemath.cpp"], # C++ 源文件路径include_dirs=[pybind11.get_include()], # pybind11 头文件language="c++",),
]setup(name="simplemath",version="0.1",author="Your Name",description="A simple C++ extension for Python",ext_modules=ext_modules,zip_safe=False,
)
生成文件夹目录
其中pyd为可执行引用的Python代码。
调用时的代码:
import sys# 添加 .pyd 文件所在目录
sys.path.append(r"E:\Pycharmproject\pythonProject1\pyd")# 导入模块
import simplemath# 调用函数
print(simplemath.add(3, 5))
print(simplemath.multiply(4, 6))