您的位置:首页 > 编程语言 > Python开发

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

2006-04-15 22:56 656 查看

1.ExtendingPythonwithCorC++

Itisquiteeasytoaddnewbuilt-inmodulestoPython,ifyouknowhowtoprograminC.Suchextensionmodulescandotwothingsthatcan'tbedonedirectlyinPython:theycanimplementnewbuilt-inobjecttypes,andtheycancallClibraryfunctionsandsystemcalls.

如果知道如何使用C编程,很容易建立Python新模块。
Tosupportextensions,thePythonAPI(ApplicationProgrammersInterface)definesasetoffunctions,macrosandvariablesthatprovideaccesstomostaspectsofthePythonrun-timesystem.ThePythonAPIisincorporatedinaCsourcefilebyincludingtheheader
"Python.h"
.

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


Thecompilationofanextensionmoduledependsonitsintendeduseaswellasonyoursystemsetup;detailsaregiveninlaterchapters.

1.1ASimpleExample

一个简单的例子
Let'screateanextensionmodulecalled"spam"(thefavoritefoodofMontyPythonfans...)andlet'ssaywewanttocreateaPythoninterfacetotheClibraryfunctionsystem().1.1Thisfunctiontakesanull-terminatedcharacterstringasargumentandreturnsaninteger.WewantthisfunctiontobecallablefromPythonasfollows:

建一个"spam"的扩张模块

>>>importspam

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

Beginbycreatingafilespammodule.c.(Historically,ifamoduleiscalled"spam",theCfilecontainingitsimplementationiscalledspammodule.c;ifthemodulenameisverylong,like"spammify",themodulenamecanbejustspammify.c.)

开始创建一个spammodule.c

Thefirstlineofourfilecanbe:

#include<Python.h>

whichpullsinthePythonAPI(youcanaddacommentdescribingthepurposeofthemoduleandacopyrightnoticeifyoulike).

Warning:SincePythonmaydefinesomepre-processordefinitionswhichaffectthestandardheadersonsomesystems,youmustincludePython.hbeforeanystandardheadersareincluded.
第一行应该是#include<Python.h>,否则可能会影响到其它
Alluser-visiblesymbolsdefinedbyPython.hhaveaprefixof"Py"or"PY",exceptthosedefinedinstandardheaderfiles.Forconvenience,andsincetheyareusedextensivelybythePythoninterpreter,
"Python.h"
includesafewstandardheaderfiles:
<stdio.h>
,
<string.h>
,
<errno.h>
,and
<stdlib.h>
.Ifthelatterheaderfiledoesnotexistonyoursystem,itdeclaresthefunctionsmalloc(),free()andrealloc()directly.

ThenextthingweaddtoourmodulefileistheCfunctionthatwillbecalledwhenthePythonexpression"spam.system(string)"isevaluated(we'llseeshortlyhowitendsupbeingcalled):

添加C函数:

staticPyObject*

spam_system(PyObject*self,PyObject*args)

{

constchar*command;

intsts;


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

returnNULL;

sts=system(command);

returnPy_BuildValue("i",sts);

}

ThereisastraightforwardtranslationfromtheargumentlistinPython(forexample,thesingleexpression
"ls-l"
)totheargumentspassedtotheCfunction.TheCfunctionalwayshastwoarguments,conventionallynamedselfandargs.

C函数总是有两个参数,分别是selfandargs.

TheselfargumentisonlyusedwhentheCfunctionimplementsabuilt-inmethod,notafunction.Intheexample,selfwillalwaysbeaNULLpointer,sincewearedefiningafunction,notamethod.(Thisisdonesothattheinterpreterdoesn'thavetounderstandtwodifferenttypesofCfunctions.)

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

TheargsargumentwillbeapointertoaPythontupleobjectcontainingthearguments.Eachitemofthetuplecorrespondstoanargumentinthecall'sargumentlist.TheargumentsarePythonobjects--inordertodoanythingwiththeminourCfunctionwehavetoconvertthemtoCvalues.ThefunctionPyArg_ParseTuple()inthePythonAPIcheckstheargumenttypesandconvertsthemtoCvalues.ItusesatemplatestringtodeterminetherequiredtypesoftheargumentsaswellasthetypesoftheCvariablesintowhichtostoretheconvertedvalues.Moreaboutthislater.

Args参数
PyArg_ParseTuple()returnstrue(nonzero)ifallargumentshavetherighttypeanditscomponentshavebeenstoredinthevariableswhoseaddressesarepassed.Itreturnsfalse(zero)ifaninvalidargumentlistwaspassed.InthelattercaseitalsoraisesanappropriateexceptionsothecallingfunctioncanreturnNULLimmediately(aswesawintheexample).

[align=center][/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: