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

Extending and Embedding the Python Interpreter(四)

阅读更多

I promised to show how spam_system() is called from Python programs. First, we need to list its name and address in a ``method table'':

 

static PyMethodDef SpamMethods[] = {
    ...
    {"system",  spam_system, METH_VARARGS,
     "Execute a shell command."},
    ...
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

Note the third entry ("METH_VARARGS"). This is a flag telling the interpreter the calling convention to be used for the C function. It should normally always be "METH_VARARGS" or "METH_VARARGS | METH_KEYWORDS"; a value of 0 means that an obsolete variant of PyArg_ParseTuple() is used.

现在我们来看一下如何在python函数中调用spam_system()。首先我们需要在一个方法表中列出spam_system()的名称和地址。注意第三个参数("METH_VARARGS"),它是一个标记,用来同志编译器需要调用的是一个C代码函数。通常来说这个参数会写成"METH_VARARGS" 或者 "METH_VARARGS | METH_KEYWORDS";

When using only "METH_VARARGS", the function should expect the Python-level parameters to be passed in as a tuple acceptable for parsing via PyArg_ParseTuple(); more information on this function is provided below.

如果只使用"METH_VARARGS"作为参数,那么那么函数会希望通过PyArg_ParseTuple()函数来将python中传入的参数进行解析。

The METH_KEYWORDS bit may be set in the third field if keyword arguments should be passed to the function. In this case, the C function should accept a third "PyObject *" parameter which will be a dictionary of keywords. Use PyArg_ParseTupleAndKeywords() to parse the arguments to such a function.

如果在第三个参数中加入METH_KEYWORDS的话,那么在函数参数中就需要传入关键字参数。在这种情况下,这个C函数需要接受一个PyObject指针参数作为它的第三个参数。使用PyArg_ParseTupleAndKeywords()去解析这种函数的参数。

The method table must be passed to the interpreter in the module's initialization function. The initialization function must be named initname(), where name is the name of the module, and should be the only non-static item defined in the module file:

这个方发表必须在模块的初始化函数中被传入解析器。这个初始化函数必须被命名为initname(),这里的name就是这个模块的名称,而这个函数应该是这个模块文件中唯一的非静态元素。

 

PyMODINIT_FUNC
initspam(void)
{
    (void) Py_InitModule("spam", SpamMethods);
}

Note that PyMODINIT_FUNC declares the function as void return type, declares any special linkage declarations required by the platform, and for C++ declares the function as extern "C".

注意PyMODINIT_FUNC声明这个函数没有返回值。

When the Python program imports module spam for the first time, initspam() is called. (See below for comments about embedding Python.) It calls Py_InitModule(), which creates a ``module object'' (which is inserted in the dictionary sys.modules under the key "spam"), and inserts built-in function objects into the newly created module based upon the table (an array of PyMethodDef structures) that was passed as its second argument. Py_InitModule() returns a pointer to the module object that it creates (which is unused here). It aborts with a fatal error if the module could not be initialized satisfactorily, so the caller doesn't need to check for errors.

当python程序第一次导入spam模块的时候,initspam()函数被调用。它被称作Py_InitModule(),它创建一个模块对象(这个模块将被插入到sys模块的字典中,使用spam作为关键字),另外基于方法映射表将那些方法加入到这个新创建的模块对象中。Py_InitModule()返回一个指向模块对象的指针。如果模块不能被满意的初始化,那么这个函数会产生一个fatal error将程序中止,所以函数的调用者没有必要去检查错误。

When embedding Python, the initspam() function is not called automatically unless there's an entry in the _PyImport_Inittab table. The easiest way to handle this is to statically initialize your statically-linked modules by directly calling initspam() after the call to Py_Initialize():

当在C代码中嵌入python时,initspam()函数不会被自动执行,最简单的办法是在调用Py_Initialize()函数后直接调用initspam()函数,就像下面的程序那样:

int
main(int argc, char *argv[])
{
    /* Pass argv[0] to the Python interpreter */
    Py_SetProgramName(argv[0]);

    /* Initialize the Python interpreter.  Required. */
    Py_Initialize();

    /* Add a static module */
    initspam();

分享到:
评论

相关推荐

    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 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参考手册

    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教程(原文).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 2[1].5 Documentation (19 September 20 06)

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

    python-tutorial.pdf

    如果你计划用C或C++来扩展Python,需要阅读《Extending and Embedding the Python Interpreter》以及《Python/C API Reference》。此外,市面上还有许多专门涵盖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