扩展和嵌入Python 解释器(Extending and Embedding the Python Interpreter)--第一章

1. Extending Python with C or C++

It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can't be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.

如果知道如何使用C编程,很容易建立 Python新模块。

To support extensions, the Python API (Application Programmers Interface) defines a set of functions, macros and variables that provide access to most aspects of the Python run-time system. The Python API is incorporated in a C source file by including the header "Python.h".

为支持扩展,Python API定义了一些函数,宏和变量。使用Python API,需要在C源文件里包含"Python.h"头文件。

The compilation of an extension module depends on its intended use as well as on your system setup; details are given in later chapters.

1.1   A Simple Example

一个简单的例子

Let's create an extension module called "spam" (the favorite food of Monty Python fans...) and let's say we want to create a Python interface to the C library function system().1.1This function takes a null-terminated character string as argument and returns an integer. We want this function to be callable from Python as follows:

建一个"spam"的扩张模块

>>> import spam
    
    
>>> status = spam.system("ls -l")
    
    

Begin by creating a file spammodule.c. (Historically, if a module is called "spam", the C file containing its implementation is called spammodule.c; if the module name is very long, like "spammify", the module name can be just spammify.c.)

开始创建一个spammodule.c

The first line of our file can be:

#include <Python.h>
    
    

which pulls in the Python API (you can add a comment describing the purpose of the module and a copyright notice if you like).

Warning: Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included.

第一行应该是#include <Python.h>,否则可能会影响到其它

All user-visible symbols defined by Python.h have a prefix of "Py" or "PY", except those defined in standard header files. For convenience, and since they are used extensively by the Python interpreter, "Python.h" includes a few standard header files: <stdio.h>, <string.h>, <errno.h>, and <stdlib.h>. If the latter header file does not exist on your system, it declares the functions malloc(), free() and realloc() directly.

The next thing we add to our module file is the C function that will be called when the Python expression "spam.system(string)"is evaluated (we'll see shortly how it ends up being called):

添加C函数:

static PyObject *
    
    
spam_system(PyObject *self, PyObject *args)
    
    
{
    
    
    const char *command;
    
    
    int sts;
    
    
 
    
    
    if (!PyArg_ParseTuple(args, "s", &command))
    
    
        return NULL;
    
    
    sts = system(command);
    
    
    return Py_BuildValue("i", sts);
    
    
}
    
    

There is a straightforward translation from the argument list in Python (for example, the single expression "ls -l") to the arguments passed to the C function. The C function always has two arguments, conventionally named self and args.

C函数总是有两个参数,分别是self and args.

The self argument is only used when the C function implements a built-in method, not a function. In the example, self will always be a NULL pointer, since we are defining a function, not a method. (This is done so that the interpreter doesn't have to understand two different types of C functions.)

Self参数在这个例子里是NULL指针

The args argument will be a pointer to a Python tuple object containing the arguments. Each item of the tuple corresponds to an argument in the call's argument list. The arguments are Python objects -- in order to do anything with them in our C function we have to convert them to C values. The function PyArg_ParseTuple() in the Python API checks the argument types and converts them to C values. It uses a template string to determine the required types of the arguments as well as the types of the C variables into which to store the converted values. More about this later.

Args参数

PyArg_ParseTuple() returns true (nonzero) if all arguments have the right type and its components have been stored in the variables whose addresses are passed. It returns false (zero) if an invalid argument list was passed. In the latter case it also raises an appropriate exception so the calling function can return NULL immediately (as we saw in the example).

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值