python 绑定,它是如何工作的? [英] python bindings, how does it work?
问题描述
我正在探索 Python.我对 python 绑定很好奇.谁能解释一下,你怎么可能从 Python 访问 C 库.
I am exploring python. I curious about python bindings. Could anybody explain, how it is possible that you can have access to C libraries from Python.
推荐答案
有几种方法可以从 Python 中调用用 C 编写的代码.
There are several ways to call code written in C from Python.
首先,标准库中有 ctypes 模块.它允许您加载动态链接库(Windows 上的 DLL,Linux 上的共享库 .so
)并直接从 Python 调用这些库中的函数.此类库通常是用 C 编写的.
First, there is the ctypes module in the standard library. It allows you to load a dynamic-link library (DLL on Windows, shared libraries .so
on Linux) and call functions from these libraries, directly from Python. Such libraries are usually written in C.
第二,在 CPython
的情况下,有 Python/C API.它可以通过两种主要方式使用:
Second, in case of CPython
there is the Python/C API. It can be used in two major ways:
动态链接库可以用 C 编写,这样 CPython
将把它当作一个模块(你可以将它导入你的 Python 程序).Python/C API 允许库定义用 C 编写但仍可从 Python 调用的函数.API 非常强大,提供了操作所有 Python 数据类型和访问解释器内部的函数.
A dynamic-link library can be written in C in such a way that CPython
will treat it as a module (you will be able to import it in your Python programs). The Python/C API allows the library to define functions that are written in C but still callable from Python. The API is very powerful and provides functions to manipulate all Python data types and access the internals of the interpreter.
第二种使用 C API 的方法是将 Python 嵌入到用 C 编写的程序中.然后 C 程序能够创建用 C 编写的内置模块并公开 C 函数,就像在动态链接库中一样方法.API 还允许程序执行脚本,然后可以导入和使用内置模块.这可用于创建基于 Python 的插件系统.
The second way to use the C API is to embed Python in a program written in C. The C program is then able to create built-in modules written in C and expose C functions, much like in the dynamic-link library approach. The API also allows the program to execute scripts which can then import and use the built-in modules. This can be used to create a Python based plug-in system.
绑定"使用 ctypes
实现为纯 Python 库,或者使用 Python/C API 实现为动态链接库.第二个选项有时与 SWIG 之类的工具一起使用,它通过生成锅炉板"代码或 Boost.Python 提供了 C++ API顶部的 Python/C API 使其更容易与 C++ 代码交互.
"Bindings" are implemented either as a pure Python library using ctypes
or as a dynamic-link library using Python/C API. The second option is sometimes used with tools like SWIG which make the task easier by taking care of generating the "boiler-plate" code or Boost.Python which provides a C++ API on top of Python/C API making it easier to interface with C++ code.
进一步阅读:外来函数接口
这篇关于python 绑定,它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!