制作 python 的 .pyd
文件(windows 平台的动态链接库)主要通过编译 python/c/c++ 扩展模块实现,常用于代码加密、性能优化或跨语言集成。以下是三种主流方法及详细步骤,以 cython 为主(最常用),辅以 pybind11 和 c-api 方案:
一、使用 cython(推荐,适合 python 代码转二进制)
步骤流程
1.环境准备:
安装 python(勾选 add to path
)。
安装 cython:
pip install cython
安装 c 编译器(windows 必装):
visual studio 2019+:勾选 “使用 c++ 的桌面开发” 和 msvc 编译器 。
2.编写代码:
创建 python 文件(如 example.py
):
def hello(name): print(f"hello, {name}!")
或使用 cython 语法(.pyx
文件,支持静态类型加速)。
3.创建编译脚本(setup.py
):
from setuptools import setup from cython.build import cythonize setup( name="example", ext_modules=cythonize("example.py"), # 或 "example.pyx" )
4.编译生成 .pyd
:
python setup.py build_ext --inplace
生成文件:example.cp312-win_amd64.pyd
→ 重命名为 example.pyd
。
5.调用测试:
import example example.hello("world") # 输出 "hello, world!"
二、使用 pybind11(适合 c++ 代码集成)
适用场景:需将 c++ 函数/类暴露给 python
1.安装 pybind11:
pip install pybind11
2.编写 c++ 文件(example.cpp
):
#include <pybind11/pybind11.h> namespace py = pybind11; void say_hello(const std::string &name) { std::cout << "hello, " << name << "!" << std::endl; } pybind11_module(example, m) { m.def("say_hello", &say_hello); }
3.配置 setup.py
:
from setuptools import setup, extension import pybind11 ext_modules = [ extension( 'example', ['example.cpp'], include_dirs=[pybind11.get_include()], language='c++', ), ] setup(ext_modules=ext_modules)
4.编译与调用:
python setup.py build_ext --inplace # 生成 example.pyd
三、使用 python c-api(底层控制,灵活性高)
步骤:
1.编写 c 代码(example.c
):
#include <python.h> static pyobject* hello(pyobject* self, pyobject* args) { const char* name; if (!pyarg_parsetuple(args, "s", &name)) return null; printf("hello, %s!\n", name); py_return_none; } static pymethoddef methods[] = {{"hello", hello, meth_varargs, ""}, {null, null, 0, null}}; static pymoduledef module = {pymoduledef_head_init, "example", null, -1, methods}; pymodinit_func pyinit_example(void) { return pymodule_create(&module); }
2.编译配置(setup.py
):
from setuptools import setup, extension setup(ext_modules=[extension('example', sources=['example.c'])])
3.编译命令同上
四、常见问题与注意事项
1.环境配置:
编译器缺失:安装 vs build tools 或 mingw。
头文件丢失:确认 python 安装路径下的 include
和 libs
存在。
2.文件命名规则:
.pyd
文件名必须与模块名一致(如 example.pyd
→ import example
)。
3.加密与反编译:
.pyd
为二进制文件,无法直接反编译,但需防范动态调试(配合代码混淆更安全)。
4.跨平台兼容:
.pyd
仅适用于 windows,linux 需编译为 .so
文件(方法类似)。
5.依赖处理:
若模块依赖第三方库(如 numpy),在 setup.py
中添加 include_dirs=[np.get_include()]
。
总结建议
- 首选 cython:适合纯 python 项目快速生成
.pyd
,兼顾易用性与性能。 - c++ 项目选 pybind11:简化 c++ 到 python 的绑定流程。
- 调试技巧:若编译失败,检查错误日志中的
c/c++
语法或路径问题,确保环境变量配置正确。
通过上述方法,你可将核心代码编译为 .pyd
,显著提升执行速度并保护源码逻辑。
到此这篇关于使用python生成pyd(windows动态链接库)文件的三种方法的文章就介绍到这了,更多相关python生成pyd文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论