扩展和嵌入python解释器 extending and embedding the python interpreter -凯发k8国际

`
gashero
  • 浏览: 938431 次
  • 性别:
  • 来自: 北京
博主相关
  • 博客
  • 微博
  • 相册
  • 收藏
  • 社区版块
    • ( 0)
    • ( 3)
    • ( 0)
    存档分类
    最新评论

    扩展和嵌入python解释器 extending and embedding the python interpreter

    2007年开始使用python与c的交互编程,那时分享了一篇《使用c/c 扩展python》 http://gashero.yeax.com/?p=38 。8年过去了,很多技术时过境迁,但python的扩展和嵌入技术仍然有很强大的生命力。尤其是国内外开始广泛的将python引入科学计算、计算机视觉、深度学习等领域后。对python的灵活性以及提高性能有着更高的需求。所以再次把我翻译的最新版本的文档分享出来。总计接近7万字(unicode字符),已经将原文档接近于翻译完成,剩余部分大多不是必需功能。

     

    扩展和嵌入python解释器 extending and embedding the python interpreter

    作者:

    guido van rossum

    翻译:

    gashero

    版本:

    release 2.4.4 2006-10-18

    日期:

    2007-08-14

    地址:

    目录

    • 1   使用c/c 扩展python
      • 1.1   一个简单的例子
      • 1.2   关于错误和异常
      • 1.3   回到例子
      • 1.4   模块方法表和初始化函数
      • 1.5   编译和连接
      • 1.6   在c中调用python函数
      • 1.7   解析传给扩展模块函数的参数
      • 1.8   解析传给扩展模块函数的关键字参数
      • 1.9   构造任意值
      • 1.10   引用计数
        • 1.10.1   python中的引用计数
        • 1.10.2   拥有规则
        • 1.10.3   危险的薄冰
        • 1.10.4   null指针
      • 1.11   使用c 编写扩展
      • 1.12   提供给其他模块以c api
    • 2   定义新类型
      • 2.1   基础
        • 2.1.1   给例子添加数据和方法
        • 2.1.2   为数据属性提供控制
        • 2.1.3   支持循环引用垃圾收集
        • 2.1.4   继承其他类型
      • 2.2   类型方法
        • 2.2.1   销毁与释放
        • 2.2.2   对象表达
        • 2.2.3   属性管理
        • 2.2.4   对象比较
        • 2.2.5   抽象协议支持
        • 2.2.6   弱引用支持
        • 2.2.7   更多建议
    • 3   使用distutils构建扩展
      • 3.1   发布你的扩展模块
    • 4   在windows构建扩展
      • 4.1   照着菜谱走猫步(a cookbook approach)
      • 4.2   unix与windows的不同
      • 4.3   实践中使用dll
    • 5   嵌入python到其他应用
      • 5.1   高层次嵌入
      • 5.2   超越高层嵌入:预览
      • 5.3   纯扩展
      • 5.4   扩展嵌入的python
      • 5.5   在c 中嵌入python
      • 5.6   链接必备条件

    1   使用c/c 扩展python

    如果你会用c,实现python嵌入模块很简单。利用扩展模块可做很多python不方便做的事情,他们可以直接调用c库和系统调用。

    为了支持扩展,python api定义了一系列函数、宏和变量,提供了对python运行时系统的访问支持。python的c api由c源码组成,并包含 "python.h" 头文件。

    编写扩展模块与你的系统相关,下面会详解。

    1.1   一个简单的例子

    下面的例子创建一个叫做 "spam" 的扩展模块,调用c库函数 system() 。这个函数输入一个null结尾的字符串并返回整数,可供python调用方式如下:

    >>> import spam

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

    一个c扩展模块的文件名可以直接是 模块名.c 或者是 模块名module.c 。第一行应该导入头文件:

    #include

    这会导入python api。

    warning

    因为python含有一些预处理定义,所以你必须在所有非标准头文件导入之前导入python.h 。

    python.h中所有用户可见的符号都有 pypy 的前缀,除非定义在标准头文件中。为了方便 "python.h" 也包含了一些常用的标准头文件,包括。如果你的系统没有后面的头文件,则会直接定义函数 malloc()free()realloc()

    下面添加c代码到扩展模块,当调用 "spam.system(string)" 时会做出响应:

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

    }

    调用方的python只有一个命令参数字符串传递到c函数。c函数总是有两个参数,按照惯例分别叫做 selfargs

    self 参数仅用于用c实现内置方法而不是函数。本例中, self 总是为null,因为我们定义的是个函数,不是方法。这一切都是相同的,所以解释器也就不需要刻意区分两种不同的c函数。

    args 参数是一个指向python的tuple对象的指针,包含参数。每个tuple子项对应一个调用参数。这些参数也全都是python对象,所以需要先转换成c值。函数 pyarg_parsetuple() 检查参数类型并转换成c值。它使用模板字符串检测需要的参数类型。

    pyarg_parsetuple() 正常返回非零,并已经按照提供的地址存入了各个变量值。如果出错(零)则应该让函数返回null以通知解释器出错。

    1.2   关于错误和异常

    一个常见惯例是,函数发生错误时,应该设置一个异常环境并返回错误值(null)。异常存储在解释器静态全局变量中,如果为null,则没有发生异常。异常的第一个参数也需要保存在静态全局变量中,也就是raise的第二个参数。第三个变量包含栈回溯信息。这三个变量等同于python变量 sys.exc_typesys.exc_valuesys.exc_traceback 。这对找到错误是很必要的。

    python api中定义了一些函数来设置这些变量。

    最常用的就是 pyerr_setstring() 。参数是异常对象和c字符串。异常对象一般由像 pyexc_zerodivisionerror 这样的对象来预定义。c字符串指明异常原因,并最终存储在异常的第一个参数里面。

    另一个有用的函数是 pyerr_setfromerrno() ,仅接受一个异常对象,异常描述包含在全局变量 errno 中。最通用的函数还是 pyerr_setobject() ,包含两个参数,分别为异常对象和异常描述。你不需要使用 py_incref() 来增加传递到其他函数的参数对象的引用计数。

    你可以通过 pyerr_occurred() 获知当前异常,返回当前异常对象,如果确实没有则为null。一般来说,你在调用函数时不需要调用 pyerr_occurred() 检查是否发生了异常,你可以直接检查返回值。

    如果调用更下层函数时出错了,那么本函数返回null表示错误,并且整个调用栈中只要有一处调用 pyerr_*() 函数设置异常就可以。一般来说,首先发现错误的函数应该设置异常。一旦这个错误到达了python解释器的主循环,则会中断当前执行代码并追究异常。

    有一种情况下,模块可能依靠其他 pyerr_*() 函数给出更加详细的错误信息,并且是正确的。但是按照一般规则,这并不重要,很多操作都会因为种种原因而挂掉。

    想要忽略这些函数设置的异常,异常情况必须明确的使用 pyerr_clear() 来清除。只有在c代码想要自己处理异常而不是传给解释器时才这么做。

    每次失败的 malloc() 调用必须抛出一个异常,直接调用 malloc()realloc() 的地方要调用 pyerr_nomemory() 并返回错误。所有创建对象的函数都已经实现了这个异常的抛出,所以这是每个分配内存都要做的。

    还要注意的是 pyarg_parsetuple() 系列函数的异常,(by gashero)返回一个整数状态码是有效的,0是成功,-1是失败,有如unix系统调用。

    最后,小心垃圾情理,也就是 py_xdecref()py_decref() 的调用,会返回的异常。

    选择抛出哪个异常完全是你的个人爱好了。有一系列的c对象代表了内置python异常,例如 pyexc_zerodivisionerror ,你可以直接使用。当然,你可能选择更合适的异常,不过别使用 pyexc_typeerror 告知文件打开失败(有个更合适的 pyexc_ioerror )。如果参数列表有误, pyarg_parsetuple() 通常会抛出 pyexc_typeerror 。如果参数值域有误, pyexc_valueerror 更合适一些。

    你也可以为你的模块定义一个唯一的新异常。需要在文件前部声明一个静态对象变量,如:

    static pyobject* spamerror;

    然后在模块初始化函数(initspam())里面初始化它,并省却了处理:

    pymodinit_func

    initspam(void) {

        pyobject* m;

        m=py_initmodule("spam",spammethods);

        if (m==null)

            return null;

        spamerror=pyerr_newexception("spam.error",null,null);

        py_incref(spamerror);

        pymodule_addobject(m,"error",spamerror);

    }

    注意实际的python异常名字是 spam.errorpyerr_newexception() 函数使用exception为基类创建一个类(除非是使用另外一个类替代null)。

    同样注意的是创建类保存了spamerror的一个引用,这是有意的。为了防止被垃圾回收掉,否则spamerror随时会成为野指针。

    一会讨论 pymodinit_func 作为函数返回类型的用法。

    1.3   回到例子

    回到前面的例子,你应该明白下面的代码:

    if (!pyarg_parsetuple(args,"s",&command))

        return null;

    就是为了报告解释器一个异常。如果执行正常则变量会拷贝到本地,后面的变量都应该以指针的方式提供,以方便设置变量。本例中的command会被声明为 "const char* command" 。

    下一个语句使用unix系统函数system(),传递给他的参数是刚才从 pyarg_parsetuple() 取出的:

    sts=system(command);

    我们的 spam.system() 函数必须返回一个py对象,这可以通过 py_buildvalue() 来完成,其形式与 pyarg_parsetuple() 很像,获取格式字符串和c值,并返回新的python对象:

    return py_buildvalue("i",sts);

    在这种情况下,会返回一个整数对象,这个对象会在python堆里面管理。

    如果你的c函数没有有用的返回值,则必须返回none。你可以用 py_retun_none 宏来完成:

    py_incref(py_none);

    return py_none;

    py_none 是一个c名字指定python对象none。这是一个真正的py对象,而不是null指针。

    1.4   模块方法表和初始化函数

    把函数声明为可以被python调用,需要先定义一个方法表:

    static pymethoddef spammethods[]= {

        ...

        {"system",spam_system,meth_varargs,

        "execute a shell command."},

        ...

        {null,null,0,null}    /*必须的结束符 by gashero*/

    };

    注意第三个参数 meth_varargs ,这个标志指定会使用c的调用惯例。可选值有 meth_varargsmeth_varargs | meth_keywords 。值0代表使用 pyarg_parsetuple() 的陈旧变量。

    如果单独使用 meth_varargs ,函数会等待python传来tuple格式的参数,并最终使用 pyarg_parsetuple() 进行解析。

    meth_keywords 值表示接受关键字参数。这种情况下c函数需要接受第三个 pyobject* 对象,表示字典参数,使用 pyarg_parsetupleandkeywords() 来解析出参数。

    方法表必须传递给模块初始化函数。初始化函数函数名规则为 initname() ,其中 name 为模块名。并且不能定义为文件中的static函数:

    pymodinit_func

    initspam(void) {

        (void) py_initmodule("spam",spammethods);

    }

    注意 pymodinit_func 声明了void为返回类型,还有就是平台相关的一些定义,如c 的就要定义成 extern "c"

    python程序首次导入这个模块时就会调用initspam()函数。他调用 py_initmodule() 来创建一个模块对象,同时这个模块对象会插入到 sys.modules 字典中的 "spam" 键下面。然后是插入方法表中的内置函数到 "spam" 键下面。 py_initmodule() 返回一个指针指向刚创建的模块对象。他是有可能发生严重错误的,也有可能在无法正确初始化时返回null。

    当嵌入python时, initspam() 函数不会自动被调用,除非在入口处的 _pyimport_inittab 表。最简单的初始化方法是在 py_initialize() 之后静态调用 initspam() 函数:

    int

    main(int argc, char* argv[]) {

        py_setprogramname(argv[0]);

        py_initialize();

        initspam();

        //...

    }

    在python发行版的 demo/embed/demo.c 中有可以参考的源码(by gashero)。

    note

    sys.modules 中移除模块入口,或者在多解释器环境中导入编译模块,会导致一些扩展模块出错。扩展模块作者应该特别注意初始化内部数据结构。同时要注意 reload() 函数可能会被用在扩展模块身上,并调用模块初始化函数,但是对动态状如对象(动态链接库),却不会重新载入。

    更多关于模块的现实的例子包含在python源码包的modules/xxmodule.c中。这些文件可以用作你的代码模板,或者学习。脚本 modulator.py 包含在源码发行版或windows安装中,提供了一个简单的gui,用来声明需要实现的函数和对象,并且可以生成供填入的模板。脚本在 tools/modulator/ 目录。查看readme以了解用法。

    1.5   编译和连接

    如果使用动态载入,细节依赖于系统,查看关于构建扩展模块部分,和关于在windows下构建扩展的细节。

    如果你无法使用动态载入,或者希望模块成为python的永久组成部分,就必须改变配置并重新构建解释器。幸运的是,这对unix来说很简单,只要把你的代码(例如spammodule.c)放在 modules/ python源码目录下,然后增加一行到文件 modules/setup.local 来描述你的文件即可:

    spam spammodule.o

    然后重新构建解释器,使用make。你也可以在 modules/ 子目录使用make,但是你接下来首先要重建makefile文件,使用 make makefile 命令。这对你改变 setup 文件来说很重要。

    如果你的模块需要其他扩展模块连接,则需要在配置文件后面加入,如:

    spam spammodule.o -lx11

    1.6   在c中调用python函数

    迄今为止,我们一直把注意力集中于让python调用c函数,其实反过来也很有用,就是用c调用python函数。这在回调函数中尤其有用。如果一个c接口使用回调,那么就要实现这个回调机制。

    幸运的是,python解释器是比较方便回调的,并给标准python函数提供了标准接口。这里就不再详述解析python代码作为输入的方式,如果有兴趣可以参考 python/pythonmain.c 中的 -c 命令代码。

    调用python函数,首先python程序要传递python函数对象。当调用这个函数时,用全局变量保存python函数对象的指针,还要调用 py_incref() 来增加引用计数,当然不用全局变量也没什么关系。例如如下:

    static pyobject* my_callback=null;

    static pyobject*

    my_set_callback(pyobject* dummy, pyobject* args) {

        pyobject* result=null;

        pyobject* temp;

        if (pyarg_parsetuple(args,"o:set_callback",&temp)) {

            if (!pycallable_check(temp)) {

                pyerr_setstring(pyexc_typeerror,"parameter must be callable");

                return null;

            }

            py_xincref(temp);

            py_xincref(my_callback);

            my_callback=temp;

            py_incref(py_none);

            result=py_none;

        }

        return result;

    }

    这个函数必须使用 meth_varargs 标志注册到解释器。宏 py_xincref()py_xdecref() 增加和减少对象的引用计数。

    然后,就要调用函数了,使用 pyeval_callobject() 。这个函数有两个参数,都是指向python对象:python函数和参数列表。参数列表必须总是tuple对象,如果没有参数则要传递空的tuple。使用 py_buildvalue() 时,在圆括号中的参数会构造成tuple,无论有没有参数,如:

    int arg;

    pyobject* arglist;

    pyobject* result;

    //...

    arg=123;

    //...

    arglist=py_buildvalue("(i)",arg);

    result=pyeval_callobject(my_callback,arglist);

    py_decref(arglist);

    pyeval_callobject() 返回一个python对象指针表示返回值。 pyeval_callobject()引用计数无关 的,有如例子中,参数列表对象使用完成后就立即减少引用计数了。pyeval_callobject() 返回一个python对象指针表示返回值。 pyeval_callobject()引用计数无关 的,有如例子中,参数列表对象使用完成后就立即减少引用计数了。

    pyeval_callobject() 的返回值总是新的,新建对象或者是对已有对象增加引用计数。所以你必须获取这个对象指针,在使用后减少其引用计数,即便是对返回值没有兴趣也要这么做。但是在减少这个引用计数之前,你必须先检查返回的指针是否为null。如果是null,则表示出现了异常并中止了(by gashero)。如果没有处理则会向上传递并最终显示调用栈,当然,你最好还是处理好异常。如果你对异常没有兴趣,可以用 pyerr_clear() 清除异常,例如:

    if (result==null)

        return null;  /*向上传递异常*/

    //使用result

    py_decref(result);

    依赖于具体的回调函数,你还要提供一个参数列表到 pyeval_callobject() 。在某些情况下参数列表是由python程序提供的,通过接口再传到回调函数。这样就可以不改变形式直接传递。另外一些时候你要构造一个新的tuple来传递参数。最简单的方法就是 py_buildvalue() 函数构造tuple。例如,你要传递一个事件对象时可以用:

    pyobject* arglist;

    //...

    arglist=py_buildvalue("(l)",eventcode);

    result=pyeval_callobject(my_callback,arglist);

    py_decref(arglist);

    if (result==null)

        return null;  /*一个错误*/

    /*使用返回值*/

    py_decref(result);

    注意 py_decref(arglist) 所在处会立即调用,在错误检查之前。当然还要注意一些常规的错误,比如 py_buildvalue() 可能会遭遇内存不足等等。

    1.7   解析传给扩展模块函数的参数

    函数 pyarg_parsetuple() 声明如下:

    int pyarg_parsetuple(pyobject* arg, char* format, ...);

    参数 arg 必须是一个tuple对象,包含传递过来的参数, format 参数必须是格式化字符串,语法解释见 "python c/api" 的5.5节。剩余参数是各个变量的地址,类型要与格式化字符串对应。

    注意 pyarg_parsetuple() 会检测他需要的python参数类型,却无法检测传递给他的c变量地址,如果这里出错了,可能会在内存中随机写入东西,小心。

    任何python对象的引用,在调用者这里都是 借用的引用 ,而不增加引用计数。

    一些例子:

    int ok;

    int i,j;

    long k,l;

    const char* s;

    int size;

    ok=pyarg_parsetuple(args,"");

    /* python call: f() */

     

    ok=pyarg_parsetuple(args,"s",&s);

    /* python call: f('whoops!') */

     

    ok=pyarg_parsetuple(args,"lls",&k,&l,&s);

    /* python call: f(1,2,'three') */

     

    ok=pyarg_parsetuple(args,"(ii)s#",&i,&j,&s,&size);

    /* python call: f((1,2),'three') */

     

    {

        const char* file;

        const char* mode="r";

        int bufsize=0;

        ok=pyarg_parsetuple(args,"s|si",&file,&mode,&bufsize);

        /* python call:

            f('spam')

            f('spam','w')

            f('spam','wb',100000)

        */

    }

     

    {

        int left,top,right,bottom,h,v;

        ok=pyarg_parsetuple(args,"((ii)(ii))(ii)",

            &left,&top,&right,&bottom,&h,&v);

        /* python call: f(((0,0),(400,300)),(10,10)) */

    }

     

    {

        py_complex c;

        ok=pyarg_parsetuple(args,"d:myfunction",&c);

        /* python call: myfunction(1 2j) */

    }

    1.8   解析传给扩展模块函数的关键字参数

    函数 pyarg_parsetupleandkeywords() 声明如下:

    int pyarg_parsetupleandkeywords(pyobject* arg, pyobject* kwdict, \

        char* format, char* kwlist[],...);

    参数arg和format定义同 pyarg_parsetuple() 。参数 kwdict 是关键字字典,用于接受运行时传来的关键字参数。参数 kwlist 是一个null结尾的字符串,定义了可以接受的参数名,并从左到右与format中各个变量对应。如果执行成功 pyarg_parsetupleandkeywords() 会返回true,否则返回false并抛出异常。

    note

    嵌套的tuple在使用关键字参数时无法生效,不在kwlist中的关键字参数会导致 typeerror 异常。

    如下是使用关键字参数的例子模块,作者是 geoff philbrick ():

    #include "python.h"

     

    static pyobject*

    keywdarg_parrot(pyobject* self, pyobject* args, pyobject* keywds) {

        int voltage;

        char* state="a stiff";

        char* action="voom";

        char* type="norwegian blue";

        static char* kwlist[]={"voltage","state","action","type",null};

        if (!pyarg_parsetupleandkeywords(args,keywds,"i|sss",kwlist,

                &voltage,&state,&action,&type))

            return null;

        printf("-- this parrot wouldn't %s if you put %i volts through it.\n",action,voltage);

        printf("-- lovely plumage, the %s -- it's %s!\n",type,state);

        py_incref(py_none);

        return py_none;

    }

     

    static pymethoddef keywdary_methods[]= {

        /*注意pycfunction,这对需要关键字参数的函数很必要*/

        {"parrot",(pycfunction)keywdarg_parrot, \

            meth_varargs | meth_keywords, \

            "print a lovely skit to standard output."},

        {null,null,0,null}

    };

     

    void

    initkeywdarg(void) {

        py_initmodule("keywdarg",keywdarg_methods);

    }

    1.9   构造任意值

    这个函数声明与 pyarg_parsetuple() 很相似,如下:

    pyobject* py_buildvalue(char* format, ...);

    接受一个格式字符串,与 pyarg_parsetuple() 相同,但是参数必须是原变量的地址指针。最终返回一个python对象适合于返回给python代码(by gashero)。

    一个与 pyarg_parsetuple() 的不同是,后面可能需要的要求返回一个tuple,比如用于传递给其他python函数以参数。 py_buildvalue() 并不总是生成tuple,在多于1个参数时会生成tuple,而如果没有参数则返回none,一个参数则直接返回该参数的对象。如果要求强制生成一个长度为空的tuple,或包含一个元素的tuple,需要在格式字符串中加上括号。

    例如:

    代码

    返回值

    py_buildvalue("")

    none

    py_buildvalue("i",123)

    123

    py_buildvalue("iii",123,456,789)

    (123,456,789)

    py_buildvalue("s","hello")

    'hello'

    py_buildvalue("ss","hello","world")

    ('hello', 'world')

    py_buildvalue("s#","hello",4)

    'hell'

    py_buildvalue("()")

    ()

    py_buildvalue("(i)",123)

    (123,)

    py_buildvalue("(ii)",123,456)

    (123,456)

    py_buildvalue("(i,i)",123,456)

    (123,456)

    py_buildvalue("[i,i]",123,456)

    [123,456]

    py_buildvalue("{s:i,s:i}",'a',1,'b',2)

    {'a':1,'b':2}

    py_buildvalue("((ii)(ii))(ii)",1,2,3,4,5,6)

    (((1,2),(3,4)),(5,6))

    1.10   引用计数

    在c/c 语言中,程序员负责动态分配和回收堆(heap)当中的内存。这意味着,我们在c中编程时必须面对这个问题。

    每个由 malloc() 分配的内存块,最终都要由 free() 扔到可用内存池里面去。而调用 free() 的时机非常重要,如果一个内存块忘了 free() 则是内存泄漏,程序结束前将无法重新使用。而如果对同一内存块 free() 了以后,另外一个指针再次访问,则叫做野指针。这同样会导致严重的问题。

    内存泄露往往发生在一些并不常见的程序流程上面,比如一个函数申请了资源以后,却提前返回了,返回之前没有做清理工作。人们经常忘记释放资源,尤其对于后加新加的代码,而且会长时间都无法发现。这些函数往往并不经常调用,而且现在大多数机器都有庞大的虚拟内存,所以内存泄漏往往在长时间运行的进程,或经常被调用的函数中才容易发现。所以最好有个好习惯加上代码约定来尽量避免内存泄露。

    python往往包含大量的内存分配和释放,同样需要避免内存泄漏和野指针。他选择的方法就是 引用计数 。其原理比较简单:每个对象都包含一个计数器,计数器的增减与引用的增减直接相关,当引用计数为0时,表示对象已经没有存在的意义了,就可以删除了。

    一个叫法是 自动垃圾回收 ,引用计数是一种垃圾回收方法,用户必须要手动调用 free() 函数。优点是可以提高内存使用率,缺点是c语言至今也没有一个可移植的自动垃圾回收器。引用计数却可以很好的移植,有如c当中的 malloc()free() 一样。也许某一天会出现c语言饿自动垃圾回收器,不过在此之前我们还得用引用计数。

    python使用传统的引用计数实现,不过他包含一个循环引用探测器。这允许应用不需要担心的直接或间接的创建循环引用,而这实际上是引用计数实现的自动垃圾回收的致命缺点。循环引用指对象经过几层引用后回到自己,导致了其引用计数总是不为0。传统的引用计数实现无法解决循环引用的问题,尽管已经没有其他外部引用了。

    循环引用探测器可以检测出垃圾回收中的循环并释放其中的对象。只要python对象有 __del__() 方法,python就可以通过 gc module 模块来自动暴露出循环引用。gc模块还提供 collect() 函数来运行循环引用探测器,可以在配置文件或运行时禁用循环应用探测器。

    循环引用探测器作为一个备选选项,默认是打开的,可以在构建时使用 --without-cycle-gc 选项加到 configure 上来配置,或者移除 pyconfig.h 文件中的 with_cycle_gc 宏定义。在循环引用探测器禁用后,gc模块将不可用。

    1.10.1   python中的引用计数

    有两个宏 py_incref(x)py_decref(x) 用于增减引用计数。 py_decref() 同时会在引用计数为0时释放对象资源。为了灵活性,他并不是直接调用 free() 而是调用对象所在类型的析构函数。

    一个大问题是何时调用 py_incref(x)py_decref(x) 。首先介绍一些术语。没有任何人都不会 拥有 一个对象,只能拥有其引用。对一个对象的引用计数定义了引用数量。拥有的引用,在不再需要时负责调用 py_decref() 来减少引用计数。传递引用计数有三种方式:传递、存储和调用 py_decref() 。忘记减少拥有的引用计数会导致内存泄漏。

    同样重要的一个概念是 借用 一个对象,借用的对象不能调用 py_decref() 来减少引用计数。借用者在不需要借用时,不保留其引用就可以了。应该避免拥有者释放对象之后仍然访问对象,也就是野指针。

    借用的优点是你无需管理引用计数,缺点是可能被野指针搞的头晕。借用导致的野指针问题常发生在看起来无比正确,但是事实上已经被释放的对象。

    借用的引用也可以用 py_incref() 来改造成拥有的引用。这对引用的对象本身没什么影响,但是拥有引用的程序有责任在适当的时候释放这个拥有。

    1.10.2   拥有规则

    一个对象的引用进出一个函数时,其引用计数也应该同时改变。

    大多数函数会返回一个对对象拥有的引用。而且几乎所有的函数其实都会创建一个对象,例如 pyint_fromlong()py_buildvalue() ,传递一个拥有的引用给接受者。即便不是刚创建的,你也需要接受一个新的拥有引用。一般来说, pyint_fromlong() 会维护一个常用值缓存,并且返回缓存项的引用。

    很多函数提取一些对象的子对象并传递拥有引用,例如 pyobject_getattrstring() 。另外,小心一些函数,包括: pytuple_getitem()pylist_getitem()pydict_getitem()pydict_getitemstring() ,他们返回的都是借用的引用。

    函数 pyimport_addmodule() 也是返回借用的引用,尽管他实际上创建了对象,只不过其拥有的引用实际存储在了 sys.modules 中。

    当你传递一个对象的引用到另外一个函数时,一般来说,函数是借用你的引用,如果他确实需要存储,则会使用 py_incref() 来变为拥有引用。这个规则有两种可能的异常: pytuple_setitem()pylist_setitem() ,这两个函数获取传递给他的拥有引用,即便是他们执行出错了。不过 pydict_setitem() 却不是接收拥有的引用。

    当一个c函数被py调用时,使用对参数的借用。调用者拥有参数对象的拥有引用。所以,借用的引用的寿命是函数返回。只有当这类参数必须存储时,才会使用 py_incref() 变为拥有的引用。

    从c函数返回的对象引用必须是拥有的引用,这时的拥有者是调用者。

    1.10.3   危险的薄冰

    有些使用借用的情况会出现问题。这是对解释器的盲目理解所导致的,因为拥有者往往提前释放了引用。

    首先而最重要的情况是使用 py_decref() 来释放一个本来是借用的对象,比如列表中的元素:

    void

    bug(pyobject* list) {

        pyobject* item=pylist_getitem(list,0);

        pylist_setitem(list,1,pyint_fromlong(0l));

        pyobject_print(item,stdout,0); /* bug! */

    }

    这个函数首先借用了 list[0] ,然后把 list[1] 替换为值0,最后打印借用的引用。看起来正确么,不是!

    我们来跟踪一下 pylist_setitem() 的控制流,列表拥有所有元素的引用,所以当项目1被替换时,他就释放了原始项目1。而原始项目1是一个用户定义类的实例,假设这个类定义包含 __del__() 方法。如果这个类的实例引用计数为1,处理过程会调用 __del__() 方法。

    因为使用python编写,所以 __del__() 中可以用任何python代码来完成释放工作。替换元素的过程会执行 del list[0] ,即减掉了对象的最后一个引用,然后就可以释放内存了。

    知道问题后,凯发k8国际娱乐官网入口的解决方案就出来了:临时增加引用计数。正确的版本如下:

    void

    no_bug(pyobject* list) {

        pyobject* item=pylist_getitem(list,0);

        py_incref(item);

        pylist_setitem(list,1,pyint_fromlong(0l));

        pyobject_print(item,stdout,0);

        py_decref(item);

    }

    这是一个真实的故事,旧版本的python中多处包含这个问题,让guido花费大量时间研究 __del__() 为什么失败了。

    第二种情况的问题出现在多线程中的借用引用。一般来说,python中的多线程之间并不能互相影响对方,因为存在一个gil。不过,这可能使用宏 py_begin_allow_threads 来临时释放锁,最后通过宏 py_end_allow_threads 来再申请锁,这在io调用时很常见,允许其他线程使用处理器而不是等待io结束。很明显,下面的代码与前面的问题相同:

    void

    bug(pyobject* list) {

        pyobject* item=pylist_getitem(list,0);

        py_begin_allow_threads

        //一些io阻塞调用

        py_end_allow_threads

        pyobject_print(item,stdout,0); /*bug*/

    }

    1.10.4   null指针

    一般来说,函数接受的参数并不希望你传递一个null指针进来,这会出错的。函数的返回对象引用返回null则代表发生了异常。这是python的机制,毕竟,一个函数如果执行出错了,那么也没有必要多解释了,浪费时间。(注:彪悍的异常也不需要解释)

    最好的测试null的方法就是在代码里面,一个指针如果收到了null,例如 malloc() 或其他函数,则表示发生了异常。

    py_incref()py_decref() 并不检查null指针,不过还好, py_xincref()py_xdecref() 会检查。

    检查特定类型的宏,形如 pytype_check() 也不检查null指针,因为这个检查是多余的。

    c函数的调用机制确保传递的参数列表(也就是args参数)用不为null,事实上,它总是一个tuple。

    而把null扔到python用户那里可就是一个非常严重的错误了。

    1.11   使用c 编写扩展

    有时候需要用c 编写python扩展模块。不过有一些严格的限制。如果python解释器的主函数是使用c编译器编译和连接的,那么全局和静态对象的构造函数将无法使用。而主函数使用c 编译器时则不会有这个问题。被python调用的函数,特别是模块初始化函数,必须声明为 extern "c" 。没有必要在python头文件中使用 extern "c" 因为在使用c 编译器时会自动加上 __cplusplus 这个定义,而一般的c 编译器一般都会设置这个符号。

    1.12   提供给其他模块以c api

    很多模块只是提供给python使用的函数和新类型,但是偶尔也有可能被其他扩展模块所调用。例如一个模块实现了 "collection" 类型,可以像list一样工作而没有顺序。有如标准python中的list类型一样,提供的c接口可以让扩展模块创建和管理list,这个新的类型也需要有c函数以供其他扩展模块直接管理。

    初看这个功能可能以为很简单:只要写这些函数就行了(不需要声明为静态),提供适当的头文件,并注释c的api。当然,如果所有的扩展模块都是静态链接到python解释器的话,这当然可以正常工作。但是当其他扩展模块是动态链接库时,定义在一个模块中的符号,可能对另外一个模块来说并不是可见的。而这个可见性又是依赖操作系统实现的,一些操作系统对python解释器使用全局命名空间和所有的扩展模块(例如windows),也有些系统则需要明确的声明模块的导出符号表(aix就是个例子),或者提供一个不同策略的选择(大多数的unices)。即便这些符号是全局可见的,拥有函数的模块,也可能尚未载入。

    为了可移植性,不要奢望任何符号会对外可见。这意味着模块中所有的符号都声明为 static ,除了模块的初始化函数以外,这也是为了避免各个扩展模块之间的符号名称冲突。这也意味着必须以其他方式导出扩展模块的符号。

    python提供了一种特殊的机制,以便在扩展模块间传递c级别的信息(指针): cobject 。一个cobject是一个python的数据类型,存储了任意类型指针(void*)。cobject可以只通过c api来创建和存取,但是却可以像其他python对象那样来传递。在特别的情况下,他们可以被赋予一个扩展模块命名空间内的名字。其他扩展模块随后可以导入这个模块,获取这个名字的值,然后得到cobject中保存的指针。

    通过cobject有很多种方式导出扩展模块的c api。每个名字都可以得到他自己的cobject,或者可以把所有的导出c api放在一个cobject指定的数组中来发布。所以可以有很多种方法导出c api。

    如下的示例代码展示了把大部分的重负载任务交给扩展模块,作为一个很普通的扩展模块的例子。他保存了所有的c api的指针到一个数组中,而这个数组的指针存储在cobject中。对应的头文件提供了一个宏以管理导入模块和获取c api的指针,客户端模块只需要在存取c api之前执行这个宏就可以了。

    这个导出模块是修改自1.1节的spam模块。函数 spam.system() 并不是直接调用c库的函数 system() ,而是调用 pyspam_system() ,提供了更加复杂的功能。这个函数 pyspam_system() 同样导出供其他扩展模块使用。

    函数 pyspam_system() 是一个纯c函数,(by gashero)声明为static如下:

    static int

    pyspam_system(const char* command) {

        return system(command);

    }

    函数 spam_system() 做了细小的修改:

    static pyobject*

    spam_system(pyobject* self, pyobject* args) {

        const char* command;

        int sts;

        if (!pyarg_parsetuple(args,"s",&command))

            return null;

        sts=pyspam_system(command);

        return py_buildvalue("i",sts);

    }

    在模块的头部加上如下行:

    #include "python.h"

    另外两行需要添加的是:

    #define spam_module

    #include "spammodule.h"

    这个宏定义是告诉头文件需要作为导出模块,而不是客户端模块。最终模块的初始化函数必须管理初始化c api指针数组的初始化:

    pymodinit_func

    initspam(void)

    {

        pyobject *m;

        static void *pyspam_api[pyspam_api_pointers];

        pyobject *c_api_object;

     

        m = py_initmodule("spam", spammethods);

        if (m == null)

            return;

     

        /* initialize the c api pointer array */

        pyspam_api[pyspam_system_num] = (void *)pyspam_system;

     

        /* create a cobject containing the api pointer array's address */

        c_api_object = pycobject_fromvoidptr((void *)pyspam_api, null);

     

        if (c_api_object != null)

            pymodule_addobject(m, "_c_api", c_api_object);

    }

    注意 pyspam_api 声明为static,否则 initspam() 函数执行之后,指针数组就消失了。

    大部分的工作还是在头文件 spammodule.h 中,如下:

    #ifndef py_spammodule_h

    #define py_spammodule_h

    #ifdef __cplusplus

    extern "c" {

    #endif

     

    /* header file for spammodule */

     

    /* c api functions */

    #define pyspam_system_num 0

    #define pyspam_system_return int

    #define pyspam_system_proto (const char *command)

     

    /* total number of c api pointers */

    #define pyspam_api_pointers 1

     

     

    #ifdef spam_module

    /* this section is used when compiling spammodule.c */

     

    static pyspam_system_return pyspam_system pyspam_system_proto;

     

    #else

    /* this section is used in modules that use spammodule's api */

     

    static void **pyspam_api;

     

    #define pyspam_system \

     (*(pyspam_system_return (*)pyspam_system_proto) pyspam_api[pyspam_system_num])

     

    /* return -1 and set exception on error, 0 on success. */

    static int

    import_spam(void)

    {

        pyobject *module = pyimport_importmodule("spam");

     

        if (module != null) {

            pyobject *c_api_object = pyobject_getattrstring(module, "_c_api");

            if (c_api_object == null)

                return -1;

            if (pycobject_check(c_api_object))

                pyspam_api = (void **)pycobject_asvoidptr(c_api_object);

            py_decref(c_api_object);

        }

        return 0;

    }

     

    #endif

     

    #ifdef __cplusplus

    }

    #endif

     

    #endif /* !defined(py_spammodule_h) */

    想要调用 pyspam_system() 的客户端模块必须在初始化函数中调用 import_spam() 以初始化导出扩展模块:

    pymodinit_func

    initclient(void) {

        pyobject* m;

        m=py_initmodule("client",clientmethods);

        if (m==null)

            return;

        if (import_spam()<0)

            return;

        /*其他初始化语句*/

    }

    这样做的缺点是 spammodule.h 有点复杂。不过这种结构却可以方便的用于其他导出函数,所以学着用一次也就好了。

    最后需要提及的是cobject提供的一些附加函数,用于cobject指定的内存块的分配和释放。详细信息可以参考python的c api参考手册的cobject一节,和cobject的实现,参考文件 include/cobject.hobjects/cobject.c

    2   定义新类型

    程序员可以自定义类型供python操作,有如一些核心数据类型一样。

    这并不困难,所有的扩展类型代码都遵循同一个模式,但是有一些细节需要了解就是了。

    note

    定义新类型的方法在python2.2时发生了巨大的改变。本文仅描述python2.2和更新的版本的。如果需要支持太老的python,你还是找老文档去吧。

    2.1   基础

    python运行时会把所有python对象看作是pyobject*类型的指针。一个pyobject并不是一个很庞大的对象,而仅仅包含引用计数和指向 类型对象 的指针。类型对象决定了c函数从哪里调用,例如,一个属性就会查找一个对象或被其他对象使用(?)。c函数会调用 类型方法 来区别于 [].append (叫做 对象方法 )。

    所以,如果你想要定义一个新的对象类型,你需要创建类型对象。

    这个步骤可以用例子来解释,如下就是一个很小,但是完整定义的新类型。

    #include

    typedef struct {

        pyobject_head

        //这里描述各个字段

    } noddy_noddyobject;

     

    static pytypeobject noddy_noddytype={

        pyobject_head_init(null)

        0,                             //ob_size

        "noddy.noddy",                 //tp_name

        sizeof(noddy_noddyobject),     //tp_basicsize

        0,                             //tp_itemsize

        0,                             //tp_dealloc

        0,                             //tp_print

        0,                             //tp_getattr

        0,                             //tp_setattr

        0,                             //tp_compare

        0,                             //tp_repr

        0,                             //tp_as_number

        0,                             //tp_as_sequence

        0,                             //tp_as_mapping

        0,                             //tp_hash

        0,                             //tp_call

        0,                             //tp_str

        0,                             //tp_getattro

        0,                             //tp_setattro

        0,                             //tp_as_buffer

        py_tpflags_default,            //tp_flags

        "noddy objects",               //tp_doc

    };

     

    static pymethoddef noddy_methods[]={

        {null}

    };

     

    #ifndef pymodinit_func

    #define pymodinit_func void

    #endif

    pymodinit_func initnoddy(void) {

        pyobject* m;

        noddy_noddytype.tp_new=pytype_genericnew;

        if (pytype_ready(&noddy_noddytype)<0)

            return;

        m=py_initmodule3("noddy",noddy_methods,"example module with new type");

        py_incref(&noddy_noddytype);

        pymodule_addobject(m,"noddy",(pyobject*)&noddy_noddytype);

    }

    这里还有很多地方(bit)是空的,以后可以逐渐知道他们的意义。

    首先是:

    typedef struct {

        pyobject_head

    } noddy_noddyobject;

    这就是noddy需要包含的,在这种情况下没办法包含python对象以外的东西(this is what a noddy object will contain--in this case, nothing more than every python object contains),也就是一个类型对象的指针。这是由pyobject_head宏所引进的字段。在这里使用宏是为了规范化层次并且便于调试。注意,在宏 pyobject_head 后面是没有分号";"的,因为宏里面已经包含了一个了。一定要小心不注意加上的分号,因为习惯使然,你的编译器也会提示,但是其他人也许却不注意(在windows上msvc会把这个问题当作错误,并且不允许编译)。

    与之相比,我们看看标准python整数的定义:

    typedef struct {

        pyobject_head

        long ob_ival;

    } pyintobject;

    继续看看类型对象:

    static pytypeobject noddy_noddytype={

        pyobject_head_init(null)

        0,                          //ob_size

        "noddy,noddy",              //tp_name

        sizeof(noddy_noddyobject),  //tp_basicsize

        0,                          //tp_itemsize

        0,                          //tp_dealloc

        0,                          //tp_print

        0,                          //tp_getattr

        0,                          //tp_setattr

        0,                          //tp_compare

        0,                          //tp_repr

        0,                          //tp_as_number

        0,                          //tp_as_sequence

        0,                          //tp_as_mapping

        0,                          //tp_hash

        0,                          //tp_call

        0,                          //tp_str

        0,                          //tp_getattro

        0,                          //tp_setattro

        0,                          //tp_as_buffer

        py_tpflags_defaults,        //tp_flags

        "noddy objects",            //tp_doc

    };

    现在你再去看看 object.hpytypeobject 的定义,你会发现有如上的很多字段定义。剩余的字段会被c编译器以0填充,按照惯例,如果你不用他们那就别碰他们。

    这对于为未来预留功能位置比较有用:

    pyobject_head_init(null)

    这行有点恶心,(by gashero)而我们还可以这样写:

    pyobject_head_init(&pytype_type)

    作为一个类型对象type的类型,但是这些并不是总是会被c编译器接受。幸运的,是,这些空着的字段会自动被 pytype_ready() 所填充。

    0,                              //ob_size

    字段ob_size并没有用上,它放在这个位置只是为了兼容旧版本的python的扩展模块。这个字段总是设为0。

    "noddy.noddy",                  //tp_name

    这是这个类型的名字。这将会显示在默认的文本描述或者一些错误信息中,例如:

    >>> "" noddy.new_noddy()

    traceback (most recent call last):

      file "", line1, in ?

    typeerror: cannot add type "noddy.noddy" to string

    注意名字是以点号分隔的,同时包含模块名和类型名。这里的模块名是noddy,而类型是noddy,所以设置类型名为noddy.noddy。

    sizeof(noddy_noddyobject),      //tp_basicsize

    这是让python知道在调用 pyobject_new() 时分配多少内存。

    note

    如果你想要你的类型可以被子类化,并且你的类型作为基类时拥有相同的tp_basicsize,你可能在多继承时遇到问题。因为该子类会在 __bases__ 中列出自定义的类型,而且在调用 __new__ 失败时不会报出错误。想要避免这个问题可以设置一个足够大的 tp_basicsize ,至少比父类型要大。大多数时候这是正确的,无论你实例化对象,还是给基类对象添加数据成员,因此也会增加其大小。

    0,                              //tp_itemsize

    对于列表和字符串,这里应该是可变长度,不过暂时忽略。

    跳过我们没有定义的类型方法,我们设置类标志为 py_tpflags_default

    py_tpflags_default,             //tp_flags

    所有的类型都应该包含这个常量。它允许在当前python版本中所有成员定义。

    我们提供了一个doc string到 tp_doc

    "noddy objects",                //tp_doc

    现在我们看看类型方法。我们在模块中实现这些。一会的例子中展示。

    现在所作的都是为了创建noddy对象。允许对象的创建,我们必须提供一个 tp_new 的实现。我们也可以使用默认的实现,也就是 pytype_genericnew() 。只需要将其赋值到 tp_new 的位置即可。不过有些平台和c编译器实现中不允许用一个函数调用来初始化一个结构体。所以,我们将赋值放到模块初始化函数中,在 pytype_ready() 之前:

    noddy_noddytype.tp_new=pytype_genericnew;

    if (pytype_ready(&noddy_noddytype)<0)

        return;

    所有其他类型方法都是null,一会在写。

    剩余的部分都很像,除了 initnoddy() 中的一些代码:

    if (pytype_ready(&noddy_noddytype)<0)

        return;

    这会初始化noddy类型,填入成员,包括 ob_type

    pymodule_addobject(m,"noddy",(pyobject*)&noddy_noddytype);

    这回添加类型到模块字典,这样我们就可以通过如下来创建noddy的示例了:

    >>> import noddy

    >>> mynoddy=noddy.noddy()

    就这些了,剩余的就是构建了,将这些代码放到 noddy.c 中,然后 setup.py 中写:

    from distutils.core import setup,extension

    setup(name="noddy",version="1.0",

        ext_modules=[extension("noddy",["noddy.c"])])

    然后输入:

    $ python setup.py build

    这时就会在子目录产生 noddy.so ,将其放到python启动目录下,就可以按照上面的导入该模块并生成实例了。

    其实并不难,不过现在功能还不够有趣,没有数据,不能做任何事,也不能被继承。

    2.1.1   给例子添加数据和方法

    让我们给这个例子添加数据和方法。也要让着个类型可以作为基类。我们创建一个新的模块,noddy2添加这些功能:

    #include

    #include

     

    typedef struct {

        pyobject_head

        pyobject *first;

        pyobject *last;

        int number;

    } noddy;

     

    static void noddy_dealloc(noddy *self) {

        py_xdecref(self->first);

        py_xdecref(self->last);

        self->ob_type->tp_free((pyobject*)self);

    }

     

    static pyobject *noddy_new(pytypeobject *type, pyobject *args, pyobject *kwds) {

        noddy *self;

        self=(noddy*)type->tp_alloc(type,0);

        if (self!=null) {

            self->first=pystring_fromstring("");

            if (self->first==null) {

                py_decref(self);

                return null;

            }

            self->last=pystring_fromstring("");

            if (self->last==null) {

                py_decref(self);

                return null;

            }

            self->number=0;

        }

        return (pyobject*)self;

    }

     

    static int noddy_init(noddy *self, pyobject *args, pyobject *kwds) {

        pyobject *first=null, *last=null, *tmp;

        static char *kwlist[]={"first", "last", "number", null};

        if (!pyarg_parsetupleandkeywords(args, kwds, "|ooi", kwlist,

                &first, &last, &self->number))

            return -1;

        if (first) {

            tmp=self->first;

            py_incref(first);

            self->first=first;

            py_xdecref(tmp);

        }

        if (last) {

            tmp=self->last;

            py_incref(last);

            self->last=last;

            py_xdecref(tmp);

        }

        return 0;

    }

     

    static pymemberdef noddy_members[]={

        {"first",   t_object_ex,    offsetof(noddy, first), 0,  "first name"},

        {"last",    t_object_ex,    offsetof(noddy, last),  0,  "last name"},

        {"number",  t_object_ex,    offsetof(noddy, number),0,  "number"},

        {null}

    };

     

    static pyobject *noddy_name(noddy *self) {

        static pyobject *format=null;

        pyobject *args, *result;

        if (format==null) {

            format=pystring_fromstring("%s %s");

            if (format==null) //by gashero

                return null;

        }

        if (self->first==null) {

            pyerr_setstring(pyexc_attributeerror, "first");

            return null;

        }

        if (self->last==null) {

            pyerr_setstring(pyexc_attributeerror, "last");

            return null;

        }

        args=py_buildvalue("oo", self->first, self->last);

        if (args==null)

            return null;

        result=pystring_format(format, args);

        py_decref(args);

        return result;

    }

     

    static pymethoddef noddy_methods[] = {

        {"name",    (pycfunction)noddy_name,    meth_noargs,

                "return name, combining the first and last name"},

        {null}

    };

     

    static pytypeobject noddytype = {

        pyobject_head_init(null)

        0,              //ob_size

        "noddy.noddy",  //tp_name

        sizeof(noddy),  //tp_basicsize

        0,              //tp_itemsize

        (destructor)noddy_dealloc,  //tp_dealloc

        0,              //tp_print

        0,              //tp_getattr

        0,              //tp_setattr

        0,              //tp_compare

        0,              //tp_repr

        0,              //tp_as_number

        0,              //tp_as_sequence

        0,              //tp_as_mapping

        0,              //tp_hash

        0,              //tp_call

        0,              //tp_str

        0,              //tp_getattro

        0,              //tp_setattro

        0,              //tp_as_buffer

        py_tpflags_default | py_tpflags_basetype,   //tp_flags

        "noddy objects",    //tp_doc

        0,              //tp_traverse

        0,              //tp_clear

        0,              //tp_richcompare

        0,              //tp_weaklistoffset

        0,              //tp_iter

        0,              //tp_iternext

        noddy_methods,  //tp_methods

        noddy_members,  //tp_members

        0,              //tp_getset

        0,              //tp_base

        0,              //tp_dict

        0,              //tp_descr_get

        0,              //tp_descr_set

        0,              //tp_dictoffset

        (initproc)noddy_init,   //tp_init

        0,              //tp_alloc

        noddy_new,      //tp_new

    };

     

    static pymethoddef module_methods[] = {

        {null}

    };

     

    #ifndef pymodinit_func

    #define pymodinit_func void

    #endif

    pymodinit_func

    initnoddy2(void) {

        pyobjec *m;

        if (pytype_ready(&noddytype)<0)

            return;

        m=py_initmodule3("noddy2", module_methods,

                example");

        if (m==null)

            return;

        py_incref(&noddytype);

        pymodule_addobject(m, "noddy", (pyobject*)&noddytype);

    }

    开头时导入了 structmember.h 头文件。用于处理属性,稍后解释。

    noddy对象也缩写为noddy了,其类型对象是 noddytype

    noddy类型有三个数据属性,first、last、number。first和last是python字符串,number是整数。对象结构体中记录了这三个字段的实际值。

    因为有数据成员了,所以需要小心的分配和释放。至少需要释放方法(deallocation method),即 noddy_dealloc() 函数。并且指定到 tp_dealloc 成员。负责将几个对象的引用计数减少。使用 py_xdecref() 因为first和last有可能是null。随后会调用 tp_free 成员来释放对象的内存。注意对象的类型有可能不是noddy,有可能是其子类。

    我们需要确保first和last初始化为空字符串,在 noddy_new() 中做。并将该函数赋值到 tp_new 成员。

    tp_new 成员用于响应创建(create, 而不是初始化)类型的对象。暴露为python的 __new__() 方法。实现 new 方法的一个目的是所有实例值都有初始化的值。此例中,我们使用新方法来确保初始值不是null。如果我们不在乎初始值是null,则可以使用 pytype_genericnew() 作为我们的 new 方法,也就是以前所做的。 pytype_genericnew() 初始化所有的实例变量到null。

    new 方法是静态方法,传入要初始化的类型及其参数,返回新创建的对象。 new 方法总是接收可选的和关键字参数,不过通常被忽略,留下参数处理到初始化方法。注意如果类型支持子类,传递来的类型可能不是之前定义的。 new 方法调用 tp_alloc 槽来分配内存。我们并不填充 tp_alloc 槽。 pytype_ready() 会自动填充它,集成自基类,缺省是 object 。大多数类型都是默认分配的。

    如果你创建一个合作的(co-operative) tp_new (调用基类的 tp_new__new__() ),你必须不能假设调用顺序。总是静态检测你要调用的类型,并直接调用 tp_new ,或通过 type->tp_base->tp_new 。如果你不这么做,你类型的python子类也会集成python定义的类,而无法正常工作。你根本就无法创建子类的对象,而得到typerror。

    初始化方法 noddy_init() 放入 tp_init 成员。暴露为python的 __init__() 方法,用于初始化刚创建对象。不像 new 方法,我们无法确保初始化器一定被调用。初始化器在被解包时不会被调用,且可以被重载。我们的初始化器接收参数来提供初始化值。初始化器总是接受可选的和关键字参数。

    初始化器可以被多次调用。任何人可以调用 __init__() 方法。因为如此,我们必须小心的确保赋值。可能被诱惑这么干:

    if (first) {

        py_xdecref(self->first);

        py_incref(first);

        self->first=first;

    }

    但是这是有风险的。我们的类型没有严格限制first的类型,所以其可能是其他类型的对象(by gashero)。有可能在方法first成员时触发其destructor。要避免这种可能,我们总是重新赋值成员,在减少其引用计数前,原因:

    1. 当我们绝对知道引用计数大于1时
    2. 当我们知道对象的deallocation不会在我们的代码里被调用时
    3. 当tp_dealloc 在gc调用时不支持减少引用计数时

    要暴露实例属性,有多种办法,最简单的办法是定义成员定义,即 noddy_members 。然后放在 tp_members 成员。

    每个成员定义都有个成员名字,类型,偏移值,访问标识和文档字符串。

    这种方式的缺点是没法提供限制属性赋值的方法。我们期望first和last是字符串,但是任何python对象都可以被赋值。而且这些属性也可以被删除,甚至c指针到null。哪怕我们已经初始化为非null值了,成员在被删除时会被设置为null。

    定义了一个方法叫 name() ,输出first和last组合的结果。

    方法实现为一个c函数,接受noddy(或其子类)作为第一个参数。方法总是接受一个实例作为第一个参数。方法总是接受可选和关键字参数,不过此例我们不关心参数,就定义了不接受参数。有如:

    def name(self):

        return '%s %s'%(self.first, self.last)

    注意我们必须检查first和last不能是null。这是因为删除会导致成员变为null。更好的办法是检测属性值必须是string类型,下一节讨论。

    已有的定义方法也需要放到一个数组中 noddy_methods ,然后放到 tp_methods 成员。注意我们使用 meth_noargs 标识来表示不接受参数。

    最后我们定义这个类型可以作为基类,通过 py_tpflags_basetype 。一直到现在,很小心的确保了我们的对象可以被作为基类使用。

    2.1.2   为数据属性提供控制

    本节讨论如何给noddy对象的属性first和last提供控制。在前面章节的模块中,实例变量first和last可以设置为非空字符串,我们想要确保这些属性总是包含字符串。

    #include

    #include "structmember.h"

     

    typedef struct {

        pyobject_head

        pyobject *first;

        pyobject *last;

        int number;

    } noddy;

     

    static void noddy_dealloc(noddy *self) {

        py_xdecref(self->first);

        py_xdecref(self->last);

        self->ob_type->tp_free((pyobject*)self);

    }

     

    static pyobject *noddy_new(pytypeobject *type, pyobject *args, pyobject *kwds) {

        noddy *self;

        self=(noddy*)type->tp_alloc(type,0);

        if (self!=null) {

            self->first=pystring_fromstring("");

            if (self->first==null) {

                py_decref(self);

                return null;

            }

            self->last=pystring_fromstring("");

            if (self->last==null) {

                py_decref(self);

                return null;

            }

            self->number=0;

        }

        return (pyobject*)self;

    }

     

    static int noddy_init(noddy *self, pyobject *args, pyobject *kwds) {

        pyobject *first=null, *last=null, *tmp;

        static char *kwlist[]={"first","last","number", null};

        if (!pyarg_parsetupleandkeywords(args, kwds, "|ssi", kwlist,

            &first, &last, &self->number))

            return -1;

        if (first) {

            tmp=self->first;

            py_incref(first);

            self->first=first;

            py_decref(tmp);

        }

        if (last) {

            tmp=self->last;

            py_incref(last);

            self->last=last;

            py_decref(tmp);

        }

        return 0;

    }

     

    static pymemberdef noddy_members[]={

        {"number",  t_int,  offsetof(noddy,number), 0, "noddy number"},

        {null}

    };

     

    static pyobject *noddy_getfirst(noddy *self, void *closure) {

        py_incref(self->first);

        return self->first;

    }

     

    static int noddy_setfirst(noddy *self, pyobject *value, void *closure) {

        if (value==null) {

            pyerr_setstring(pyexc_typeerror, "cannot delete the first attribute");

            return -1;

        }

        if (!pystring_check(value)) {

            pyerr_setstring(pyexc_typeerror, "the first attribute value must be a string");

            return -1;

        }

        py_decref(self->first);

        py_incref(value);

        self->first=value;

        return 0;

    }

     

    static pyobject *noddy_getlast(noddy *self, void *closure) {

        py_incref(self->last);

        return self->last;

    }

     

    static int noddy_setlast(noddy *self, pyobject *value, void *closure) {

        if (value==null) {

            pyerr_setstring(pyexc_typeerror, "cannot delete the last attribute");

            return -1;

        }

        if (!pystring_check(value)) {

            pyerr_setstring(pyexc_typeerror, "the last attribute value must be a string");

            return -1;

        }

        py_decref(self->last);

        py_incref(value);

        self->last=value;

        return 0;

    }

     

    static pygetsetdef noddy_getseters[]={

        {"first",   (getter)noddy_getfirst, (setter)noddy_setfirst, "first name",   null},

        {"last",    (getter)noddy_getlast,  (setter)noddy_setlast,  "last name",    null},

        {null}

    };

     

    static pyobject *noddy_name(noddy *self) {

        static pyobject *format=null;

        pyobject *args, *result;

        if (format==null) {

            format=pystring_fromstring("%s %s");

            if (format==null)

                return null;

        }

        args=py_buildvalue("oo",self->first,self->last);

        if (args==null)

            return null;

        result=pystring_format(format,args);

        py_decref(args);

        return result;

    }

     

    static pymethoddef noddy_methods[]={

        {"name",    (pycfunction)noddy_name,    meth_noargs,    "return name"},

        {null}

    };

     

    static pytypeobject noddytype={

        pyobject_head_init(null)

        0,                      //ob_size

        "noddy.noddy",          //tp_name

        sizeof(noddy),          //tp_basicsize

        0,                      //tp_itemsize

        (destructor)noddy_dealloc,  //tp_dealloc

        0,                      //tp_print

        0,                      //tp_getattr

        0,                      //tp_setattr

        0,                      //tp_compare

        0,                      //tp_repr

        0,                      //tp_as_number

        0,                      //tp_as_sequence

        0,                      //tp_as_mapping

        0,                      //tp_hash

        0,                      //tp_call

        0,                      //tp_str

        0,                      //tp_getattro

        0,                      //tp_setattro

        0,                      //tp_as_buffer

        py_tpflags_default|py_tpflags_basetype, //tp_flags

        "noddy object",         //tp_doc

        0,                      //tp_traverse

        0,                      //tp_clear

        0,                      //tp_richcompare

        0,                      //tp_weaklistoffset

        0,                      //tp_iter

        0,                      //tp_iternext

        noddy_methods,          //tp_methods

        noddy_members,          //tp_members

        noddy_getseters,        //tp_getset

        0,                      //tp_base

        0,                      //tp_dict

        0,                      //tp_descr_get

        0,                      //tp_descr_set

        0,                      //tp_dictoffset

        (initproc)noddy_init,   //tp_init

        0,                      //tp_alloc

        noddy_new,              //tp_new

    };

     

    static pymethoddef module_methods[]={

        {null}

    };

     

    #ifndef pymodinit_func

    #define pymodinit_func void

    #endif

     

    pymodinit_func initnoddy3(void) {

        pyobject *m;

        if (pytype_ready(&noddy_type)<0)

            return;

        m=py_initmodule3("noddy3",module_methods,

            "example noddy3");

        if (m==null)

            return;

        py_incref(&noddytype);

        pymodule_addobject(m, "noddy", (pyobject*)&noddytype);

    }

    要实现更加精细的控制,可以自己修改getter和setter函数。如下就是first属性对应的set和get函数:

    noddy_getfirst(noddy *self, void *closure) {

        py_incref(self->first);

        return self->first;

    }

     

    static int noddy_setfirst(noddy *self, pyobject *value, void *closure) {

        if (value==null) {

            pyerr_setstring(pyexc_typeerror, "cannot delete the first attribute");

            return -1;

        }

        if (!pystring_check(value)) {

            pyerr_setstring(pyexc_typeerror,

                    "the first attribute value must be a string");

            return -1;

        }

        py_decref(self->first);

        py_incref(value);

        self->first=value;

        return 0;

    }

    setter和getter函数会传入noddy对象和一个 "closure" 。在这个例子里,closure会被忽略。closure用以支持定义数据时的高级用法。例如允许一组setter和getter函数决定closure里数据的设置和获取。

    setter函数传入noddy对象,新的值,以及closure。新的值可以时null,表示该属性需要被删除。在我们的setter里,如果属性被删除或传入的值不是字符串则抛出异常。

    创建一个数组 pygetsetdef 结构来声明:

    static pygetsetdef noddy_getseters[] = {

        {"first",

            (getter)noddy_getfirst, (setter)noddy_setfirst,

            "first name", null},

        {"last",

            (getter)noddy_getlast, (setter)noddy_setlast,

            "last name", null},

        {null}

    };

    并且注册到 tp_getset 槽:

    noddy_getseters,        //tp_getset

    最后要提到的是closure,这里用到时都是传入null的。

    还可以删除成员定义:

    static pymemberdef noddy_members[] = {

        {"number",  t_int, offsetof(noddy, number), 0,

            "noddy number"},

        {null}

    };

    我们还需要更新 tp_init 处理器来允许传入string:

    static int

    noddy_init(noddy *self, pyobject *args, pyobject *kwds) {

        pyobject *first=null, *last=null, *tmp;

        static char *kwlist[] = {"first", "last", "number", null};

        if (!pyarg_parsetupleandkeywords(args, kwds, "|ssi", kwlist,

                &first, &last, &self->number))

            return -1;

        if (first) {

            tmp=self->first;

            py_incref(first);

            self->first=first;

            py_decref(tmp);

        }

        if (last) {

            tmp=self->last;

            py_incref(last);

            self->last=last;

            py_decref(tmp);

        }

        return 0;

    }

    通过这些修改,我们可以确保first和last成员不会是null,所以可以在所有情况中不必检查其是否为null了。这意味着大部分的 py_xdecref() 可以改为 py_decref() 。(by gashero)唯一无法修改的地方是 dealloctor ,因为在初始化这些成员时可能会出错。

    我们也将模块初始化函数改为初始化函数,以及增加了另外的定义到 setup.py 文件。

    2.1.3   支持循环引用垃圾收集

    python有循环垃圾收集器,可以将对象在引用计数不为零时仍然标记为无用。这可以解决循环引用。例如:

    >>> l=[]

    >>> l.append(l)

    >>> del l

    在这里例子中,列表包含了他自身。当删除时,他仍然持有他自己的引用,其引用计数不会到0。幸运的是python的循环垃圾收集会实际指出该问题,并释放。

    在第二个版本的noddy例子,我们允许任何类型的对象存储到first和last属性。这意味着noddy对象可以进入循环:

    >>> import noddy2

    >>> n=noddy2.noddy()

    >>> l=[n]

    >>> n.first=l

    这很蠢,但提醒我们需要加入循环垃圾收集器到noddy的例子。要支持循环垃圾收集,类型需要填充2个槽并设置类标识允许这些槽。

    #include

    #include "structmember.h"

     

    typedef struct {

        pyobject_head

        pyobject *first;

        pyobject *last;

        int number;

    } noddy;

     

    static int

    noddy_traverse(noddy *self, visitproc visit, void *arg {

        int vert;

        if (self->first) {

            vret=visit(self->first,arg);

            if (vert!=0)

                return vert;

        }

        if (self->last) {

            vert=visit(self->last, arg);

            if (vert!=0)

                return vert;

        }

        return 0;

    }

     

    static int

    noddy_clear(noddy *self) {

        pyobject *tmp;

        tmp=self->first;

        self->first=null;

        py_xdecref(tmp);

     

        tmp=self->last;

        self->last=null;

        py_xdecref(tmp);

     

        return 0;

    }

     

    static void

    noddy_dealloc(noddy *self) {

        noddy_clear(self);

        self->ob_type->tp_free((pyobject*)self);

    }

     

    static pyobject *

    noddy_new(pytypeobject *type, pyobject *args, pyobject *kwds) {

        noddy *self;

        self=(noddy*)type->tp_alloc(type,0);

        if (self!=null) {

            self->first=pystring_fromstring("");

            if (self->first==null) {

                py_decref(self);

                return null;

            }

            self->last=pystring_fromstring("");

            if (self->last==null) {

                py_decref(self);

                return null;

            }

            self->number=0;

        }

        return (pyobject*)self;

    }

     

    static int

    noddy_init(noddy *self, pyobject *args, pyobject *kwds) {

        pyobject *first=null, *last=null, *tmp;

        static char *kwlist[] = {"first", "last", "number", null};

        if (!pyarg_parsetupleandkeywords(args, kwds, "|ooi", kwlist,

                &first, &last, &self->number))

            return -1;

        if (first) {

            tmp=self->first;

            py_incref(first);

            self->first=first;

            py_xdecref(tmp);

        }

        if (last) {

            tmp=self->last;

            py_incref(last);

            self->last=last;

            py_xdecref(tmp);

        }

        return 0;

    }

     

    static pymemberdef noddy_members[] = {

        {"first",   t_object_ex,    offsetof(noddy,first),  0,

            "first name"},

        {"last",    t_object_ex,    offsetof(noddy,last),   0,

            "last name"},

        {"number",  t_int,          offsetof(noddy,number), 0,

            "noddy number"},

        {null}

    };

    @wait 代码都没抄完呢,(by gashero)一大堆废话

    2.1.4   继承其他类型

    @wait

    2.2   类型方法

    快速了解类型方法(type method)的实现。如下是 pytypeobject 的定义,有些字段用于调试:

    typedef struct _typeobject {

        pyobject_var_head

        char *tp_name;          //用于打印

        int tp_basicsize, tp_itemsize;  //用于分配

        //标准操作的实现方法

        destructor tp_dealloc;

        printfunc tp_print;

        getattrfunc tp_getattr;

        setattrfunc tp_setattr;

        cmpfunc tp_compare;

        reprfunc tp_repr;

        //标准类的方法集合

        pynumbermethods *tp_as_number;

        pysequencemethods *tp_as_sequence;

        pymappingmehtods *tp_as_mapping;

        //更多标准操作(二进制兼容)

        hashfunc tp_hash;

        ternaryfunc tp_call;

        reprfunc tp_str;

        getattrfunc tp_getattro;

        setattrfunc tp_setattro;

        //访问对象io缓冲的函数

        pybufferprocs *tp_as_buffer;

        //定义可选和扩展操作的标识

        long tp_flags;

        char *tp_doc;       //文档字符串

        //从2.0开始的所有可访问对象调用函数

        traverseproc tp_traverse;

        //删除包含对象的引用

        inquiry tp_clear;

        //从2.1开始,富比较

        richcmpfunc tp_richcompare;

        //弱引用

        long tp_weaklistoffset;

        //从2.2开始,迭代器

        getiterfunc tp_iter;

        iternextfunc tp_iternext;

        //属性描述符和子类支持

        struct pymethoddef *tp_methods;

        struct pymemberdef *tp_members;

        struct pygetsetdef *tp_getset;

        struct _typeobject *tp_base;

        pyobject *tp_dict;

        descrgetfunc tp_descr_get;

        descrsetfunc tp_descr_set;

        long tp_dictoffset;

        initproc tp_init;

        allocfunc tp_alloc;

        newfunc tp_new;

        freefunc tp_free;

        inquiry tp_is_gc;

        pyobject *tp_bases;

        pyobject *tp_mro;

        pyobject *tp_cache;

        pyobject *tp_subclasses;

        pyobject *tp_weaklist;

    } pytypeobject;

    这里有一大堆的方法,无需担心太多,通常只需要实现一部分。

    接下来介绍各种对应的处理器。不会进入结构定义,因为这里一堆历史兼容问题,确保你的初始化按照正确的字段顺序。你可以参照该顺序,只是修改自己所需的。

    char *tp_name;  //for printing

    类型的名字,有如上节所说,会在很多地方出现,选择个有帮助的。

    int tp_basicsize, tp_itemsize;  //for allocation

    这些字段供内存分配。python对变长对象有内置支持,需要用到 tp_itemsize 字段。

    char *tp_doc;

    存放一个字符串来供 obj.__doc__ 返回文档字符串。

    现在回到基本类型方法。(by gashero)

    2.2.1   销毁与释放

    destructor tp_dealloc;

    该函数在引用计数降低到0时调用。如果你的类型有需要释放的内存或其他要执行的清理,就将其放在这里。对象本身也需要在这里释放,一个例子:

    static void

    newdatatype_dealloc(newdatatypeobject *obj) {

        free(obj->obj_underlyingdatatypeptr);

        obj->ob_type->tp_free(obj);

    }

    需要关注的点是deallocator可能会遗留异常。当deallocator将异常放到栈中,可能无人会看到这个异常,而且这个异常未必来自于哪个deallocator。这可能导致难以调试的问题。正确的做法是将未决异常放到不安全的动作之前,并在完成时恢复。可以用 pyerr_fetch()pyerr_restore() 函数:

    static void my_dealloc(pyobject *obj) {

        myobject *self=(myobject*)obj;

        pyobject *cbresult;

        if (self->my_callback!=null) {

            pyobject *err_type, *err_value, *err_traceback;

            int have_error=pyerr_occurred() ? 1 : 0;

            if (have_error)

                pyerr_fetch(&err_type, &err_value, &err_traceback);

            cbresult=pyobject_callobject(self->my_callback, null);

            if (cbresult==null)

                pyerr_writeunraisable(self->my_callback);

            else

                py_decref(cbresult);

            if (have_error)

                pyerr_restore(err_type, err_value, err_trackback);

            py_decref(self->my_callback);

        }

        obj->ob_type->tp_free((pyobject*)self);

    }

    2.2.2   对象表达

    在python里有三种方法生成对象的文本表示, repr() 函数、 str() 函数和 print 语句。对大多数对象, print 语句就等同于 str() 函数,但是其实可以指定打印到特定的 file* ,这对于打印到文件变得靠谱。

    这三个处理器是可选的,常用类型只需要实现 tp_strtp_repr 处理器即可:

    reprfunc tp_repr;

    reprfunc tp_str;

    printfunc tp_print;

    tp_repr 处理器应该返回一个字符串对象包含了实例的描述,简单的例子如:

    static pyobject *newdatatype_repr(newdatatypeobject *obj) {

        return pystring_fromformat("repr-ified_newdatatype{{size:\%d}}",

            obj->obj_underlyingdatatypeptr->size);

    }

    如果没有提供 tp_repr 处理器,解释器会提供类型的 tp_name 和一个对象的唯一值。

    tp_str 处理 str() 的请求, tp_repr 处理 repr() 的请求。这使得可以在对象上调用 str() 。实现类似于 tp_repr 函数,但是结果字符串应该是人类可读的。如果 tp_str 没有提供,就使用 tp_repr 处理器。

    如下简单例子:

    static pyobject *newdatatype_str(newdatatypeobject *obj) {

        return pystring_fromformat("stringified_newdatatype{{size:\%d}}",

            obj->obj_underlyingdatatypeptr->size);

    }

    而print功能会在需要打印实例时调用。例如,如果结点是treenode类型,则打印功能调用就是:

    print node

    还有个flags参数,只有个 py_print_raw ,会假设无需字符串转义就打印。

    打印函数接受一个文件对象作为第一个参数,你可以这样写数据到文件。

    如下是例子:

    static int

    newdatatype_print(newdatatypeobject *obj, file *fp, int flags) {

        if (flags & py_print_raw) {

            fprintf(fp, "<{newdatatype object--size: %d}>",

                    obj->obj_underlyingdatatypeptr->size);

        } else {

            fprintf(fp, "\"<{newdatatype object--size: %d}>\"",

                    obj->obj_underlyingdatatypeptr->size);

        }

        return 0;

    }

    2.2.3   属性管理

    对每个需要支持属性的对象,其类型必须提供函数来控制属性如何被解析。这需要一个函数来获取属性,另一个用来设置属性。删除一个属性时特例,对应的新值是null。

    python支持两对属性处理器,一个类型支持属性成对处理。区别是一对接受属性名字为 char* ,而另一种接受 pyobject* 。每种类型都能实现更多便利:

    getattrfunc tp_getattr;

    setattrfunc tp_setattr;

    /* ... */

    getattrofunc    tp_getattrofunc;

    setattrofunc    tp_setattrofunc;

    如果访问属性总是简单操作,有个通用的实现可以用于提供 pyobject* 版本的属性管理。实际需要一个类型相关的属性处理器来实现,自python2.2消失。因此有很多例子无需更新使用新的通用机制。

    2.2.4   对象比较

    @wait

    2.2.5   抽象协议支持

    python支持一系列抽象协议,供python c api的抽象对象层api来调用。

    一些抽象接口是在python早期定义的。数字、映射、序列协议已经成为python的一部分。其他协议加入则较晚。每种协议需要实现多个接口,旧协议作为类型对象的可选块。新协议会添加槽到主类型对象,一个标志位指定这些槽是否应该被解释器检查。标志位不应该设置为null,而应该用于表示槽,而槽可以是未填充的。

    pynumbermethods     tp_as_number;

    pysequencemethods   tp_as_sequence;

    pymappingmethods    tp_as_mapping;

    如果你希望你的对象表现的像一个数字、序列、映射,你应该将实现的结构体地址填充上。可以到python源码包里找到例子。

    hashfunc    tp_hash;

    这个函数可选提供,会返回你对象类型的哈希数字。如下是一个例子:

    static long

    newdatatype_hash(newdatatypeobject *obj) {

        long result;

        result=obj->obj_underlyingdatatypeptr->size;

        result=result*3;

        return result;

    }

     

    ternaryfunc tp_call;

    这个函数会被数据类型实例调用。例如obj1是你的数据类型的实例,而语句 obj1('hello') 就会调用 tp_call

    函数接受3个参数:

    1. arg1是数据类型实例,上例为 obj1
    2. arg2是参数元组,通过 pyarg_parsetuple() 来解析
    3. arg3是关键字参数字典,通过 pyarg_parsetupleandkeywords() 来解析,不想支持就抛出 typeerror

    如下例子实现了call函数:

    static pyobject *

    newdatatype_call(newdatatypeobject *obj, pyobject *args, pyobject kwds) {

        pyobject *result;

        char *arg1;

        char *arg2;

        char *arg3;

        if (!pyarg_parsetuple(args, "sss:call", &arg1, &arg2, &arg3)) {

            return null;

        }

        result=pystring_fromformat(

            "returning -- value: [\%d] arg1: [\%s] arg2: [\%s] arg3: [\%s]\n",

            obj->obj_underlyingdatatypeptr->size,

            arg1, arg2, arg3);

        printf("\%s", pystring_as_string(result));

        return result;

    }

    其他字段...。

    getierfunc      tp_iter;

    iternextfunc    tp_iternext;

    这些函数提供了迭代器支持。任何对象想要支持迭代其内容,都应该实现 tp_itertp_iternext 处理器。两个处理器都接受一个参数,就是对象的实例,返回新的引用。如果发生错误,应该设置异常并返回null。

    对于迭代器容器, tp_iter 处理器应该返回一个迭代器对象。迭代器对象用于管理迭代器的状态。容器可以支持多个迭代器,互相之间不影响,每次返回个新的迭代器即可。对象应该确保被迭代一次,实现者应该返回其本身新的引用,以及实现 tp_iternext 处理器。文件对象就是迭代器的例子。

    tp_iternext 处理器返回下一个对象的新的引用。如果迭代器已经到达末尾,就应该返回null而不设置异常,或 stopiteration 异常,避免异常影响性能。如果发生了错误,就应该设置异常并返回null。

    2.2.6   弱引用支持

    @wait

    2.2.7   更多建议

    大部分函数都可以不提供,写为0即可。类型定义必须提供,在 object.h 中。

    想要学习如何实现特定方法,就去解压python源码包,进入 objects 目录,搜索c源码 tp_ 前缀的即可。

    当你想要验证一个对象是否实现了,可以使用 pyobject_typecheck() 函数,一个样例如下:

    if (!pyobject_typecheck(some_object, &mytype)) {

        pyerr_setstring(pyexc_typeerror, "arg #1 not a mything");

        return null;

    }

    3   使用distutils构建扩展

    自从python1.4开始就提供一个自动构建动态载入扩展模块和自定义解释器的make文件了。自动2.0开始,这个机制不再被支持。构建自定义解释器很少用到,而构建扩展模块则更多的使用了distutils。

    使用distutils构建扩展模块需要的distutils已经是python2.x中的标准组成。distutils也同时支持二进制包,而用户并不一定需要一个编译器来安装扩展模块。

    一个distutils包包含一个驱动脚本 setup.py 。这个纯python文件一般形式如下:

    from distutils.core import setup,extension

    module1=extension('demo',sources=['demo.c'])

    setup(name='packagename',

            version='1.0',

            description='this is a demo package',

            ext_modules=[module1])

    包含一个setup.py和一个demo.c,运行:

    python setup.py build

    将会编译demo.c,并会在build目录下产生一个"demo"扩展模块。依赖于系统,模块会在一个子目录build/lib.system中,并把名字叫做demo.so或demo.pyd。

    在setup.py,所有执行操作依靠 setup() 函数的调用。接受一大堆关键字参数,上面的例子只是使用了一些子集。一般来说,要指明包的内容。还要指明包含附加模块,有如python源码模块,文档,子包等。参考distutils了解更多。本章只是描述构建扩展模块的基础而已。

    最好把需要填入 setup() 的参数先计算好再填入,有如上面的 ext_modules 参数就是如此。例子中,这个实例定义了一个叫做"demo"的扩展模块。

    在很多情况下,构建扩展模块比较复杂,包含很多预处理指令和链接库。下面示范了一下:

    from distutils.core import setup,extension

    module1=extension('demo',

            define_macros=[('major_version','1'),

                           ('minor_version','0'),

                          ]

            include_dirs=['/usr/local/lib',],

            libraries=['tcl83'],

            library_dirs=['/usr/local/lib',],

            sources=['demo.c',])

    setup(name='packagename',

          version='1.0',

          description='this is a demo package',

          author='martin v. loewis',

          author_email='martin@v.loewis.de',

          url='http://www.python.org/doc/current/ext/building.html',

          long_description='long description',

          ext_modules=[module1])

    这个例子里面,setup附带了很多参数,指定了预处理定义,各类文件夹等。依赖于编译器,distutils用不同的方法传递信息。例如,在unix上,可能的结果如下:

    gcc -dndebug -g -o3 -wall -wstrict-prototypes -fpic -dmajor_version=1 \

        -dminor_version=0 -i/usr/local/include -i/usr/local/include/python2.2 \

        -c demo.c -o build/temp.linux-i686-2.2/demo.o

    gcc -shared build/temp.linux-i686-2.2/demo.o -l/usr/local/lib -ltcl83 \

        -o build/lib.linux-i686-2.2/demo.so

    当然,这些行只是用于演示,你应该相信distutils会做出正确的判断。

    3.1   发布你的扩展模块

    扩展模块构建完成之后,你可以用三种方法使用。

    最终用户可以直接安装模块,如:

    python setup.py install

    模块发行人员可以发布源码包:

    python setup.py sdist

    在某些情况下,附加文件需要加入到源码包里面,这通过 manifest.in 文件实现,查看distutils的文档。

    如果源码发行版构建成功,模块发行人员还可以创建二进制发行版,依赖于具体平台,可以用如下:

    python setup.py bdist_wininst

    python setup.py bdist_rpm

    python setup.py bdist_dumb

    4   在windows构建扩展

    本章解释如何在windows下使用vc 创建python扩展(by gashero),并给出一些背景资料解释如何运行。这些知识对大家都有用。

    模块作者一般推荐使用distutils来构造扩展模块,而不是本章所描述的。但是你仍然需要有个c编译器,这里就是vc 。

    note

    本章提到的一些文件名可能包含python版本号。这些文件名带有2位数字的版本号,分别为主版本号和次版本号。。例如python2.2.1的这2个数字就是22。

    4.1   照着菜谱走猫步(a cookbook approach)

    在windows上编译扩展有两种方式,有如unix上一样:用distutils或者手动。使用distutils方式对大多数模块工作的很好,可以参考distutils的手册。本节仅介绍手动编译c/c 编写的python扩展模块。

    要构建扩展模块,你首先要拥有与你版本相同的python源码,你还需要一个vc ,工程文件是供vc 7.1使用的,但是你也可以使用老版本的vc 。注意的是,你必须使用编译python相同版本的vc 来编译扩展模块。例子文件 pc\example_nt\ 描述了一个例子。

    1. 复制例子文件
      把那个文件夹拷出来,以防玷污了那个文件夹。
    2. 打开工程
      在vc 中打开工程文件example.sln。
    3. 构建例子的dll
      为了检查是否ok了,可以尝试先构建一下:
      1. 选择一个配置文件,release或debug,默认为debug。
      2. 构建dll,就是build一下。
    4.  
    5. 测试debug模式的dll
      得到了调试构建以后,就可以在dll所在的文件夹下打开python解释器:
      c>..\..\pcbuild\python_d
    6. adding parser accelerators ...
    7. done.
    8. python 2.2 (#28, dec 19 2001, 23:26:37) [msc 32 bit (intel)] on win32
    9. type "凯发k8国际 copyright", "credits" or "license" for more information.
    10. >>> import example
    11. [4897 refs]
    12. >>> example.foo()
    13. hello, world
    14. [4903 refs]
    15. >>>

    16. 恭喜,你已经成功的构建了这个扩展模块。
    17. 创建自己的工程
      创建一个目录,然后把这些源文件拷进去。文件名并不一定需要与模块名有什么必然联系,但是模块的初始化函数必须与模块名相关-你可以导入
      spam 依赖于初始化函数名为 initspam() ,并且他会调用 py_initmodule() 函数,并传递 spam 这个名字作为首参数。只是按照习俗,它一般是在spam.c或者spammodule.c中。输出文件可以叫做 spam.dllspam.pyd (后一种.pyd方式是为了防止与系统dll文件重名导致混乱)。调试模式的文件名为 spam_d.dllspam_d.pyd
      现在你可以拷贝原工程文件后修改或重新创建一个新的工程。
      同时还要拷贝
      example_nt\example.defspam\spam.def ,然后修改 spam.def 的第二行包含 initspam 。如果创建了新工程则需要自己添加 spam.def 文件,别怕这个文件就2行。另一个方法是根本不去创建.def文件,而是添加 /export:initspam 到连接器选项,可以手动修改工程配置。
    18. 创建全新工程
      创建一个vc 工作空间,选择vc -> win32 -> win32 project,然后选择工程名和存放路径,确保存放路径与刚才的那个路径相同,在python源码树中,就是在pc目录下,并且有相同的include路径设置。选择win32平台,然后ok。
      你现在就可以创建
      spam.def 了,然后添加源文件,添加进来 spam.cspam.def 然后就是ok了。
      打开工程选项。确保每个需要定制的位置都修改好。需啊则c/c 这个tab页面,选择通用范畴的弹出菜单,输入如下附加的include路径:
      ..\include,..\pc

    19. 然后修改通用范畴的连接器tab页面,然后输入:
      ..\pcbuild

    20. 另外还需要一些其他设置。在release配置页的连接tab页,选择输入框,然后添加 pythonxx.lib 到附加依赖框(additional dependencies)。
      选择debug配置页的也同样添加
      pythonxy_d.lib 文件到附加依赖。然后选择c/c 的tab页,选择代码生成,选择"multi-threaded debug dll"选项作为运行时。
      选择release页面同样选择多线程dll运行时。

    如果你的模块创建了新的类型,你可能在这一行碰钉子:

    pyobject_head_init(&pytype_type)

    需要改成:

    pyobject_head_init(null)

    并且添加如下到模块初始化函数中:

    myobject_type.ob_type=&pytype_type;

    参考python faq的第三节了解更多。

    4.2   unix与windows的不同

    unix与windows在载入运行时代码方面完全不同。

    在unix,动态载入的代码包含在共享对象文件(.so)中。当这个文件载入时,程序会自动在内存中重新定位函数和数据的位置。这是基本的动态连接操作。

    在windows,动态载入代码包含在动态链接库当中(.dll)。(by gashero)获取这些函数的地址需要一个查找表,所以dll代码的指针并不需要运行时重定位;而是在代码表中填入已经重定位的函数和数据地址。

    在unix中,只有一种链接库(.a),包含一些目标文件(.o)。当链接用于创建共享对象文件(.so)时,连接器会查找标识符的位置。然后会在最终的.so文件包含所有标识符的定义。

    在windows,有两种库。静态库和导入库(尽管都叫做.lib)。静态库有如unix的.a文件,包含重要代码。导入库仅仅使用连接器提供的标识符,也就是加载时提供的查找表。所以连接器使用导入库构建查找表。

    如果你想构建两种动态载入模块,b和c,并可能共享代码块a。在unix你需要传递a.a到b.so和c.so的连接过程,这会导致两次包含,b和c都包含他们自己对a的拷贝。在windows,构造一个a.dll同时会构造一个a.lib。你可以传递a.lib到连接器b和c。a.lib并不包含代码,仅包含a代码的运行时查找表。

    在windows,使用导入库有如 import spam ,给出要导入的名字,但是并不创建一个单独的拷贝。在unix,连接一个静态库更像是 from spam import * ,他包含单独的拷贝。

    4.3   实践中使用dll

    windows python基于vc 构建,使用其他编译器可能不会工作,下面都是基于vc 讲解。

    当在windows下创建dll时,你必须传递pythonxy.lib到连接器。来构建两个dll,spam和ni(在spam中使用的c函数),你可以使用如下命令:

    cl /ld /i/python/include spam.c ../libs/pythonxy.lib

    cl /ld /i/python/include ni.c spam.lb ../libs/pythonxy.lib

    第一个命令生成3个文件 spam.objspam.dllspam.lib 。其中 spam.dll 并不包含python函数(比如 pyarg_parsetuple() ),但是它依赖 pythonxy.lib 知道如何去找到这些python代码。

    第二个命令创建了 ni.dll (和附带的.obj和.lib),他知道如何找到spam的函数定义,并且可以找到python的执行。

    并不是所有的标识符都会导出到查找表。如果你想要python看到你的标识符,就需要以 _declspec(dllexport) 来前缀声明,比如 void _declspec(dllexport) initspam(void)pyobject _declspec(dllexport) *nigetspamdata(void)

    vc 会导入一大堆你并不需要的库,增加超过100kb的文件尺寸,想要扔掉这些导入,打开工程属性对话框的link页面,忽略缺省导入库。添加必须的 msvcrtxx.lib 到库列表就可以了。

    5   嵌入python到其他应用

    前面的章节讨论如何扩展python,如何生成适合的c库等。不过还有另一种情况:通过将python嵌入c/c 应用以扩展程序的功能。python嵌入实现了一些使用python更合适的功能。这可以有很多用途,一个例子是允许用户裁减需要的python功能。也可以用于默写使用python编写更加方便的功能。

    嵌入python与扩展很像。扩展python时,主程序是python解释器,但是嵌入python则主程序并不是python的-是程序的其他部分调用python来实现一些功能。

    所以,如果要嵌入python,你可以提供自己的主程序,这个主程序需要初始化python解释器。至少需要调用函数 py_initialize() (对于macos,调用 pymac_initialize())。可以选择是否传入命令行参数到python。然后你就可以在应用的任何地方调用python解释器了。

    有几种方法调用解释器:可以传递一个包含python语句的字符串到 pyrun_simplestring() ,也可以传递一个stdio文件指针和一个文件名(用于识别错误信息)到 pyrun_simplefile() 。你也可以调用前几章介绍的底层操作直接控制python对象。

    可以在目录 demo/embed/ 中找到嵌入python的例子。

    5.1   高层次嵌入

    嵌入python最简单的形式是使用高层次的接口。这个接口专门用于执行python脚本,而不需要与应用程序直接交互。例子可以在一个文件中展示:

    #include

    int

    main(int argc, char* argv[]) {

        py_initialize();

        pyrun_simplestring("from time import time,ctime\n"

                "print 'today is',ctime(time())\n");

        py_finalize();

        return 0;

    }

    如上代码首先使用 py_initialize() 初始化python解释器,随后执行硬编码中的python脚本来打印日期和时间。最后 py_finalize() 关闭了解释器。在真实应用中,你可能希望从其他方式获取python脚本,文件、编辑器、数据库等。从文件获取的方式更适合使用 pyrun_simplefile() 函数,可以省去分配内存空间和载入文件的麻烦。

    5.2   超越高层嵌入:预览

    高层次的接口可以方便的执行python代码,但是交换数据就很麻烦。如果需要,你可以使用低层次的接口调用。虽然多写一些c代码,但是却可以完成很多功能。

    仍然要提醒的是,python的扩展与嵌入其实很像,尽管目的不同。前几章讨论的大多数问题在这里也同样适用。可以参考用c扩展python时一些步骤:

    1. 转换python类型到c类型
    2. 传递参数并调用c函数
    3. 转换返回值到python

    当嵌入python时,接口需要做:

    1. 转换c数据到python
    2. 调用python接口程序来调用python函数
    3. 转化返回值到c

    有如你所见,数据转换的步骤用于跨语言的数据交换。唯一的不同是两次数据转换之间调用的函数。当扩展时,你调用c函数,当嵌入时,调用python函数。

    这一章不会讨论python和c之间的数据转换。并且假设你会使用手册来处理错误,自此只会讨论与扩展解释器不同的部分,你可以到前面的章节找到需要的信息。

    5.3   纯扩展

    第一个程序是执行一段python脚本中的函数。有如高层接口一节,python解释器并不会自动与程序结合。

    运行一段python脚本中的函数的代码如下:

    #include

     

    int

    main(int argc, char *argv[])

    {

        pyobject *pname, *pmodule, *pdict, *pfunc;

        pyobject *pargs, *pvalue;

        int i;

     

        if (argc < 3) {

            fprintf(stderr,"usage: call pythonfile funcname [args]\n");

            return 1;

        }

     

        py_initialize();

        pname = pystring_fromstring(argv[1]);

        /* error checking of pname left out */

     

        pmodule = pyimport_import(pname);

        py_decref(pname);

     

        if (pmodule != null) {

            pfunc = pyobject_getattrstring(pmodule, argv[2]);

            /* pfunc is a new reference */

     

            if (pfunc && pycallable_check(pfunc)) {

                pargs = pytuple_new(argc - 3);

                for (i = 0; i < argc - 3; i) {

                    pvalue = pyint_fromlong(atoi(argv[i 3]));

                    if (!pvalue) {

                        py_decref(pargs);

                        py_decref(pmodule);

                        fprintf(stderr, "cannot convert argument\n");

                        return 1;

                    }

                    /* pvalue reference stolen here: */

                    pytuple_setitem(pargs, i, pvalue);

                }

                pvalue = pyobject_callobject(pfunc, pargs);

                py_decref(pargs);

                if (pvalue != null) {

                    printf("result of call: %ld\n", pyint_aslong(pvalue));

                    py_decref(pvalue);

                }

                else {

                    py_decref(pfunc);

                    py_decref(pmodule);

                    pyerr_print();

                    fprintf(stderr,"call failed\n");

                    return 1;

                }

            }

            else {

                if (pyerr_occurred())

                    pyerr_print();

                fprintf(stderr, "cannot find function \"%s\"\n", argv[2]);

            }

            py_xdecref(pfunc);

            py_decref(pmodule);

        }

        else {

            pyerr_print();

            fprintf(stderr, "failed to load \"%s\"\n", argv[1]);

            return 1;

        }

        py_finalize();

        return 0;

    }

    这段代码从argv[1]中载入python脚本,并且调用argv[2]中的函数,整数型的参数则是从argv数组后面得来的。如果编译和链接这个程序,执行如下脚本:

    def multiply(a,b):

        print "will compute",a,"times",b

        c=0

        for i in range(0,a)

            c=c b

        return c

    结果将是:

    $ call multiply multiply 3 2

    will compute 3 times 2

    result of call: 6

    虽然这个程序的代码挺多的,但是大部分其实都是做数据转换和错误报告。主要关于嵌入python的开始于:

    py_initialize();

    pname=pystring_fromstring(argv[1]);

    /* error checking of pname left out */

    pmodule=pyimport_import(pname);

    初始化解释器之后,使用 pyimport_import() 导入模块。这个函数需要字符串作为参数,使用 pystring_fromstring() 来构造:

    pfunc=pyobject_getattrstring(pmodule,argv[2]);

    /* pfunc is a new reference */

    if (pfunc && pycallable_check(pfunc)) {

        ...

    }

    py_xdecref(pfunc);

    载入了模块以后,就可以通过 pyobject_getattrstring() 来获取对象。如果名字存在并且可以执行则可以安全的调用它。程序随后构造参数元组,然后执行调用:

    pvalue=pyobject_callobject(pfunc,pargs);

    函数调用之后,pvalue要么是null,要么是返回值的对象引用。注意在检查完返回值之后要释放引用。

    5.4   扩展嵌入的python

    至今为止,嵌入的python解释器还不能访问应用程序本身的功能。python的api允许扩展嵌入的python的解释器。所以,python可以获得其所嵌入的程序的功能。这听起来挺麻烦的,其实并不是那样。只要简单的忘记是应用程序启动了python解释器。

    可以把程序看作一对功能的集合,可以写一些胶水代码来来让python访问这些功能,有如你在写一个普通的python扩展一样。例如:

    static int numargs=0;

     

    /* return the number of arguments of the application command line */

    static pyobject*

    emb_numargs(pyobject *self, pyobject *args)

    {

        if(!pyarg_parsetuple(args, ":numargs"))

            return null;

        return py_buildvalue("i", numargs);

    }

     

    static pymethoddef embmethods[] = {

        {"numargs", emb_numargs, meth_varargs,

         "return the number of arguments received by the process."},

        {null, null, 0, null}

    };

    添加上面的代码到 main() 函数。同样,插入如下两个语句到 py_initialize() 函数之后:

    numargs=argc;

    py_initmodule("emb",embmethods);

    这两行代码初始化numargs变量,(by gashero)并且使得 emb.numargs() 函数更加易于被python嵌入的解释器所理解。通过这个扩展,python脚本可以做如下事情:

    import emb

    print "number of arguments",emb.numargs()

    在实际的应用程序中,方法需要导出api以供python使用。

    5.5   在c 中嵌入python

    有时候需要将python嵌入到c 程序中,而你必须有一些要注意的c 系统的细节,一般来说你要为这个程序写一个main()函数,然后使用c 编译器来编译和链接程序。而这里不需要因为使用c 而重新编译python本身。

    5.6   链接必备条件

    configure 脚本执行时,可以正确的生成动态链接库使用的导出符号,而这些却不会自动被嵌入的静态链接的python所继承,至少是在unix。这是用于静态链接运行库(libpython.a)并且需要载入动态扩展(.so)的方式。

    问题是一些入口点是使用python运行时定义的而仅供扩展模块使用。如果嵌入应用不使用任何这些入口点,一些链接器不会包含这些实体到最终可执行文件的符号表(by gashero)。一些附加的选项可以用于告知连接器不要删除这些符号。

    对于不同的平台,想要正确的检测该使用何种参数是非常困难的,但是幸运的是python配置好了这些值。只要通过已经安装的python解释器,启动交互解释器然后执行如下会话即可:

    >>> import distutils.sysconfig

    >>> distutils.sysconfig.get_config_var('linkforshared')

    '-xlinker -export-dynamic'

    字符串的内容就是生成的选项。如果字符串为空,则不需要任何的附加选项。linkforshared的定义与python顶层makefile中的同名变量相同。

    1
    1
    分享到:
    评论
    1 楼 2015-08-02  
    学习了 谢谢

    相关推荐

      php extending and embedding

      sams extending and embedding php

      php extending and embedding<中文翻译版>

      通往php之路的web高手必看之书,本人在研究... ...《extending and embedding php》 这本书是分析php源码,教你写扩展的,比较低层。 两本都是sams出版的极品,已转成pdf方便打印, 是英文版的,看清楚,原计原味噢 - -!

      extending and embedding php-english chm格式 有需要php扩展开发的,可以下载

      teach user how to extend for php scripts

      这是两本学习php的经典书籍,书的格式为pdf,为英文版的,大家一起研究php的奥妙啊!

      深入php内核及扩展开发英文chm extending.and.embedding.php

      embedding the python interpreter and python/c api reference. there are also several books covering python in depth. 需要有关标准对象和模块的详细介绍的话,请查询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 有基本的...

      英语php教材,英语能力强的朋友可以读。 很适合初学者。

      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

      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 有基本的认识...

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

      i the python language 1 a tutorial introduction 2 lexical conventions and syntax 3 types and objects 4 operators and expressions 5 control flow ...27 extending and embedding python index

      python is the high-level language of choice for hackers and software security analysts because it makes it easy to write powerful and effective security tools. a follow-up to the perennial best-seller...

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

      of the book deals with hacking web applications, starting with your own custom tooling in chapter 5 and then extending the popular burp suite in chapter 6. from there we will spend a great deal of ...

      extending and embedding tutorial for c/c programmers python/c api reference for c/c programmers installing python modules information for installers & sys-admins distributing python modules ...

    global site tag (gtag.js) - google analytics
    网站地图