`
DYER
  • 浏览: 50450 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Extending and Embedding the Python Interpreter(一)

阅读更多

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().This function takes a null-terminated character string as argument and returns an integer. We want this function to be callable from Python as follows:

 

>>> import spam
>>> status = spam.system("ls -l")
现在我们为C语言编写的库函数system实现一个python接口,使用方式如上述代码所示
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></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).

在spammodule.c文件的开头加入 #include <python.h></python.h> ,它的作用是将python API导入;必须先于其它标准头文件导入python API。

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<stdlib.h></stdlib.h>. If the latter header file does not exist on your system, it declares the functions malloc(), free() and realloc() directly

在python.h头文件中已经include <stdio.h></stdio.h>stdio.h, string.h, errno.h, 和stdlib.h<stdlib.h></stdlib.h>几个头文件。

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):

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和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参数只在C语言编写得函数用来实现方法时使用,实现为函数时不使用。在这个例子中,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参数是一个指向python tuple对象的指针,这个tuple对象包含所有的参数。这些对象都是python对象,当我们要在C代码中操作这些对象时我们需要将这些对象转化为C对象。python api中的PyArg_ParseTuple()函数用来检查这些对象的类别并将它们转化为C对象。

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).

如果所有的参数都有正确的类别并且被存储进设定的变量中,那么PyArg_ParseTuple() 函数返回true。如果有无效参数,那么该函数返回false。


分享到:
评论

相关推荐

    Python-3-0-1

    It is a companion to Extending and Embedding the Python Interpreter (in Extending and Embedding Python), which describes the general principles of extension writing but does not document the API ...

    Python 2.71 Document

    Welcome! This is the ...Extending and embedding the python interpreter Python /C API reference Manual Installing python modules Documenting Python Python HOWTOs Python Frequently Asked questions

    Python库参考手册.pdf

    Finally, the manual entitled Extending and Embedding the Python Interpreter describes how to add new extensions to Python and how to embed it in other applications. 本手册的读者要对Python 有基本的...

    Python参考手册

    Finally, the manual entitled Extending and Embedding the Python Interpreter describes how to add new extensions to Python and how to embed it in other applications. 本手册的读者要对Python 有基本的认识...

    Python in a Nutshell. A Desktop Quick Reference

    The book focuses on Python’s cross-platform capabilities and covers the basics of extending Python and embedding it in other applications. How This Book Is Organized This book has five parts, as ...

    Python教程(原文).doc

    而关于使用C或C++扩展Python功能,建议阅读《Extending and Embedding the Python Interpreter》和《Python/C API Reference》。 Python不仅适合处理大型项目,提供比shell脚本更强的结构和错误检查,而且它的高阶...

    Python教程(原文).pdf

    对于使用C或C++扩展Python功能,"Extending and Embedding the Python Interpreter"和"Python/C API Reference"是重要的参考资料。 教程中的“开胃菜”部分指出,Python特别适合那些需要在shell脚本的基础上增加...

    python-tutorial.pdf

    如果你计划用C或C++来扩展Python,需要阅读《Extending and Embedding the Python Interpreter》以及《Python/C API Reference》。此外,市面上还有许多专门涵盖Python编程的书籍,这些资源能够进一步提升你的技能和...

    Python 2[1].5 Documentation (19 September 20 06)

    3. **Extending and Embedding the Python Interpreter**:这部分内容主要针对想要在Python之外的环境中使用Python或扩展Python功能的开发者。它讲解了如何用C或C++编写Python扩展模块,以及如何在其他应用程序中...

    Tutorial Python

    对于希望使用C或C++扩展Python解释器的开发者,《Extending and Embedding the Python Interpreter》与《Python/C API Reference》是必读之选。这两份文档详细介绍了如何利用C语言增强Python的功能,以及如何将...

    python3.6.5参考手册 chm

    PEP 486: Make the Python Launcher aware of virtual environments PEP 488: Elimination of PYO files PEP 489: Multi-phase extension module initialization Other Language Changes New Modules typing ...

    Mayavi 参考

    The embedded Python interpreter Recording Mayavi actions to a script Command line arguments mlab: Python scripting for 3D plotting A demo 3D Plotting functions for numpy arrays 0D and 1D data 2D ...

Global site tag (gtag.js) - Google Analytics