python 扩展——迹忆客-ag捕鱼王app官网
您使用任何编译语言(如 c、c 或 java)编写的任何代码都可以集成或导入到另一个 python 脚本中。此代码被视为“扩展”。
python 扩展模块只不过是一个普通的 c 库。在 unix 机器上,这些库通常以.so结尾(用于共享对象)。在 windows 机器上,您通常会看到.dll(用于动态链接库)。
编写扩展的先决条件
要开始编写扩展,您将需要 python 头文件。
- 在 unix 机器上,这通常需要安装特定于开发人员的软件包,例如python2.5-dev。
- windows 用户在使用二进制 python 安装程序时将这些标头作为包的一部分。
此外,假设您对 c 或 c 有很好的了解,可以使用 c 编程编写任何 python 扩展。
先看一个python扩展
第一次查看 python 扩展模块时,您需要将代码分为四部分 -
- 头文件python.h。
- 您希望作为模块接口公开的 c 函数。
- 将 python 开发人员看到的函数名称映射到扩展模块内的 c 函数的表。
- 一个初始化函数。
头文件python.h
您需要在 c 源文件中包含python.h头文件,这样您就可以访问用于将模块连接到解释器的内部 python api。
确保在您可能需要的任何其他头文件之前包含 python.h。您需要遵循包含要从 python 调用的函数。
c 函数
函数的 c 实现的签名始终采用以下三种形式之一 -
static pyobject *myfunction( pyobject *self, pyobject *args );
static pyobject *myfunctionwithkeywords(pyobject *self,
pyobject *args,
pyobject *kw);
static pyobject *myfunctionwithnoargs( pyobject *self );
前面的每个声明都返回一个 python 对象。python 中没有像 c 中那样的void函数。如果你不希望你的函数返回一个值,那么返回 python 的none值 。python 头文件定义了一个宏 py_return_none
,它为我们做这件事。
c 函数的名称可以是你喜欢的任何名称,因为它们在扩展模块之外永远不会出现。它们被定义为静态函数。
您的 c 函数通常通过将 python 模块和函数名称组合在一起来命名,如下所示 -
static pyobject *module_func(pyobject *self, pyobject *args) {
/* do your stuff here. */
py_return_none;
}
这是一个在模块module 中称为func的 python 函数。您将把指向 c 函数的指针放入通常出现在源代码中的模块的方法表中。
方法映射表
这个方法表是一个简单的 pymethoddef 结构数组。该结构看起来像这样 -
struct pymethoddef {
char *ml_name;
pycfunction ml_meth;
int ml_flags;
char *ml_doc;
};
这是该结构成员的描述 -
- ml_name - 这是 python 解释器在 python 程序中使用时呈现的函数名称。
- ml_meth - 这必须是具有前一节中描述的任何一个签名的函数的地址。
- ml_flags - 这告诉解释器 ml_meth 正在使用三个签名中的哪一个。
- 该标志的值通常为 meth_varargs。
- 如果你想允许关键字参数进入你的函数,这个标志可以与 meth_keywords 进行按位或运算。
- 这也可以有一个 meth_noargs 值,表示您不想接受任何参数。
- ml_doc - 这是函数的文档字符串,如果你不想写,它可以是 null。
该表需要用一个由 null 和 0 值组成的适当成员的标记终止。
例子
对于上面定义的函数,我们有以下方法映射表 -
static pymethoddef module_methods[] = {
{ "func", (pycfunction)module_func, meth_noargs, null },
{ null, null, 0, null }
};
初始化函数
扩展模块的最后一部分是初始化函数。该函数在模块加载时由 python 解释器调用。需要将该函数命名为init module,其中module是模块的名称。
初始化函数需要从您将要构建的库中导出。python 头文件定义了 pymodinit_func 以包含适当的咒语,以便在我们编译的特定环境中发生这种情况。您所要做的就是在定义函数时使用它。
您的 c 初始化函数通常具有以下整体结构 -
pymodinit_func initmodule() {
py_initmodule3(func, module_methods, "docstring...");
}
下面是py_initmodule3函数的描述-
- func - 这是要导出的函数。
- module_methods - 这是上面定义的映射表名称。
- docstring - 这是你想在你的扩展中给出的注释。
将所有这些放在一起看起来如下所示 -
#include
static pyobject *module_func(pyobject *self, pyobject *args) {
/* do your stuff here. */
py_return_none;
}
static pymethoddef module_methods[] = {
{ "func", (pycfunction)module_func, meth_noargs, null },
{ null, null, 0, null }
};
pymodinit_func initmodule() {
py_initmodule3(func, module_methods, "docstring...");
}
例子
一个利用上述所有概念的简单示例 -
#include
static pyobject* helloworld(pyobject* self) {
return py_buildvalue("s", "hello, python extensions!!");
}
static char helloworld_docs[] =
"helloworld( ): any message you want to put here!!\n";
static pymethoddef helloworld_funcs[] = {
{"helloworld", (pycfunction)helloworld,
meth_noargs, helloworld_docs},
{null}
};
void inithelloworld(void) {
py_initmodule3("helloworld", helloworld_funcs,
"extension module example!");
}
这里py_buildvalue函数用于构建 python 值。将上述代码保存在 hello.c 文件中。我们将看到如何编译和安装这个模块以从 python 脚本调用。
构建和安装扩展
该distutils的包使得它很容易分发python模块,无论是纯python和扩展模块,以标准的方式。模块以源代码形式分发,并通过通常称为setup.py的安装脚本构建和安装,如下所示。
对于上述模块,您需要准备以下 setup.py 脚本 -
from distutils.core import setup, extension
setup(name='helloworld', version='1.0', \
ext_modules=[extension('helloworld', ['hello.c'])])
现在,使用以下命令执行所有需要的编译和链接步骤,使用正确的编译器和链接器命令和标志,并将生成的动态库复制到适当的目录中 -
$ python setup.py install
在基于 unix 的系统上,您很可能需要以 root 身份运行此命令才能获得写入 site-packages 目录的权限。这在 windows 上通常不是问题。
导入扩展
安装扩展程序后,您将能够在 python 脚本中导入和调用该扩展程序,如下所示 -
#!/usr/bin/python
import helloworld
print helloworld.helloworld()
这将产生以下结果 -
hello, python extensions!!
传递函数参数
由于您很可能希望定义接受参数的函数,因此您可以为 c 函数使用其他签名之一。例如,接受一些参数的以下函数将被定义如下 -
static pyobject *module_func(pyobject *self, pyobject *args) {
/* parse args and do something interesting here. */
py_return_none;
}
包含新函数条目的方法表如下所示 -
static pymethoddef module_methods[] = {
{ "func", (pycfunction)module_func, meth_noargs, null },
{ "func", module_func, meth_varargs, null },
{ null, null, 0, null }
};
您可以使用 api pyarg_parsetuple函数从传递给 c 函数的一个 pyobject 指针中提取参数。
pyarg_parsetuple 的第一个参数是 args 参数。这是您将要解析的对象。第二个参数是一个格式字符串,描述了您期望它们出现的参数。每个参数由格式字符串中的一个或多个字符表示,如下所示。
static pyobject *module_func(pyobject *self, pyobject *args) {
int i;
double d;
char *s;
if (!pyarg_parsetuple(args, "ids", &i, &d, &s)) {
return null;
}
/* do something interesting here. */
py_return_none;
}
编译模块的新版本并导入它使您能够使用任意数量的任何类型的参数调用新函数 -
module.func(1, s="three", d=2.0)
module.func(i=1, d=2.0, s="three")
module.func(s="three", d=2.0, i=1)
你可能会想出更多的变化。
pyarg_parsetuple 函数
这是pyarg_parsetuple函数的标准签名-
int pyarg_parsetuple(pyobject* tuple,char* format,...)
此函数返回 0 表示错误,返回不等于 0 的值表示成功。tuple 是 pyobject*,它是 c 函数的第二个参数。这里的格式是一个 c 字符串,描述了强制和可选参数。
这是pyarg_parsetuple函数的格式代码列表-
code | c type | 意义 |
---|---|---|
c | char | 长度为 1 的 python 字符串变为 c 字符。 |
d | double | python float 变为 c double。 |
f | float | python 浮点数变为 c 浮点数。 |
i | int | python int 变为 c int。 |
l | long | python int 变成了 c long。 |
l | long long | python int 变成 c long long |
o | pyobject* | 获取对 python 参数的非 null 借用引用。 |
s | char* | 没有嵌入空值的 python 字符串到 c char*。 |
s# | char* int | 任何 python 字符串到 c 地址和长度。 |
t# | char* int | 只读单段缓冲区到 c 地址和长度。 |
u | py_unicode* | 没有嵌入空值的 python unicode 到 c。 |
u# | py_unicode* int | 任何 python unicode c 地址和长度。 |
w# | char* int | 读/写单段缓冲区到 c 地址和长度。 |
z | char* | 与 s 一样,也接受 none(将 c char* 设置为 null)。 |
z# | char* int | 与 s# 一样,也接受 none(将 c char* 设置为 null)。 |
(...) | as per ... | python 序列被视为每个项目一个参数。 |
: | 格式结束,然后是错误消息的函数名称。 | |
; | 格式结束,后跟整个错误消息文本。 |
返回值
py_buildvalue采用与pyarg_parsetuple非常相似的格式字符串。不是传入正在构建的值的地址,而是传入实际值。这是一个显示如何实现添加功能的示例 -
static pyobject *foo_add(pyobject *self, pyobject *args) {
int a;
int b;
if (!pyarg_parsetuple(args, "ii", &a, &b)) {
return null;
}
return py_buildvalue("i", a b);
}
这就是如果在 python 中实现的样子 -
def add(a, b):
return (a b)
您可以按如下方式从函数中返回两个值,这将使用 python 中的列表捕获。
static pyobject *foo_add_subtract(pyobject *self, pyobject *args) {
int a;
int b;
if (!pyarg_parsetuple(args, "ii", &a, &b)) {
return null;
}
return py_buildvalue("ii", a b, a - b);
}
这就是如果在 python 中实现的样子 -
def add_subtract(a, b):
return (a b, a - b)
py_buildvalue函数
这是py_buildvalue函数的标准签名-
pyobject* py_buildvalue(char* format,...)
这里的格式是一个 c 字符串,用于描述要构建的 python 对象。py_buildvalue的以下参数是构建结果的 c 值。pyobject *结果是一个新的参考。
下表列出了常用的代码字符串,其中零个或多个连接成字符串格式。
code | c type | 意义 |
---|---|---|
c | char | c char 成为长度为 1 的 python 字符串。 |
d | double | c double 成为 python 浮点数。 |
f | float | c 浮点数变为 python 浮点数。 |
i | int | c int 变成 python int。 |
l | long | c long 变成 python int。 |
n | pyobject* | 传递一个 python 对象并窃取一个引用。 |
o | pyobject* | 传递一个 python 对象并照常对其进行 incref。 |
o& | convert void* | 任意转换 |
s | char* | c 0-terminated char* 到 python 字符串,或 null 到 none。 |
s# | char* int | c char* 和长度为 python 字符串,或 null 为 none。 |
u | py_unicode* | c 范围内,以空字符结尾的字符串到 python unicode,或 null 到无。 |
u# | py_unicode* int | c-wide 字符串和长度为 python unicode,或 null 为 none。 |
w# | char* int | 读/写单段缓冲区到 c 地址和长度。 |
z | char* | 与 s 一样,也接受 none(将 c char* 设置为 null)。 |
z# | char* int | 与 s# 一样,也接受 none(将 c char* 设置为 null)。 |
(...) | as per ... | 从 c 值构建 python 元组。 |
[...] | as per ... | 从 c 值构建 python 列表。 |
{...} | as per ... | 从 c 值、交替键和值构建 python 字典。 |
代码 {...} 从偶数个 c 值(交替键和值)构建字典。例如, py_buildvalue("{issi}",23,"zig","zag",42)
返回一个类似于 python 的 {23:'zig','zag':42} 的字典。