Python绑定,它是如何工作的? [英] python bindings, how does it work?

查看:120
本文介绍了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 code。

There are several ways to call code written in C from Python.

首先,在标准库中的 ctypes的模块。它可以让你加载动态链接库(DLL在Windows上,共享库的.so 在Linux上),并从这些库调用的函数,直接从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:

一个动态链接库可以用这样一种方式,CPython中将把它作为一个模块用C写的(你可以导入你的Python程序)。 Python的/ C API允许库的定义都写在C,但仍然可以在Python调用的函数。 API非常飞机的强大动力,并提供了函数来处理所有的Python数据类型和跨preTER访问兴田内部。

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 poweful and provides functions to manipulate all Python data types and access hte 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动态链接库。第二种选择有时像痛饮这使任务更容易通过采取产生了样板照顾$ C $工具使用C或 Boost.Python的提供关于Python / C API之上的C ++ API使其更容易与C ++ code接口。

"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆