Location:Home >> News >> system

为 Python 写一个 C++ 扩展模块

用 C 语言编写 Python 模块允许你将计算密集型代码转移到 C,同时保留 Python 的易用性。

使用 C 扩展为 Python 提供特定功能。

在前一篇文章中,我介绍了 六个 Python 解释器。在大多数系统上,CPython 是默认的解释器,而且根据民意调查显示,它还是最流行的解释器。Cpython 的独有功能是使用扩展 API 用 C 语言编写 Python 模块。用 C 语言编写 Python 模块允许你将计算密集型代码转移到 C,同时保留 Python 的易用性。

在本文中,我将向你展示如何编写一个 C++ 扩展模块。使用 C++ 而不是 C,因为大多数编译器通常都能理解这两种语言。我必须提前说明缺点:以这种方式构建的 Python 模块不能移植到其他解释器中。它们只与 CPython 解释器配合工作。因此,如果你正在寻找一种可移植性更好的与 C 语言模块交互的方式,考虑下使用 ctypes 模块。

源代码

和往常一样,你可以在 GitHub 上找到相关的源代码。仓库中的 C++ 文件有以下用途:

  • my_py_module.cpp: Python 模块MyModule 的定义
  • my_cpp_class.h: 一个头文件 - 只有一个暴露给 Python 的 C++ 类
  • my_class_py_type.h/cpp: Python 形式的 C++ 类
  • pydbg.cpp: 用于调试的单独应用程序

本文构建的 Python 模块不会有任何实际用途,但它是一个很好的示例。

构建模块

在查看源代码之前,你可以检查它是否能在你的系统上编译。我使用 CMake 来创建构建的配置信息,因此你的系统上必须安装 CMake。为了配置和构建这个模块,可以让 Python 去执行这个过程:

Special Reminder & Disclaimer:
The information of this website comes from the Internet. The content (pictures, videos and words) released by this website is mainly the content submitted by users and reproduced by users. The purpose is to convey more information, which does not mean that this website agrees with its views. The originality, statements, and content of this article have not been verified by this website. We do not guarantee or promise the authenticity, completeness, or timeliness of this article or all or part of its content or text. Please verify the relevant content on your own. This website does not assume direct or joint liability for infringement of such works. If any content on this website infringes on your rights, please contact us promptly (email: nssa@soufind.com )This site will complete the processing within 72 hours. The original content on this website cannot be reproduced without permission, or the source must be indicated when reprinting: nssa.vip Aerospace Alliance

Author:

Recommended for you

Post comments

admin

Contact Us

Contact Us

Online consultation: QQ交谈

Email: service#soufind.com

follow us on WeChat
Scan and follow us on WeChat

Scan and follow us on WeChat