扩展和嵌入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().
建一个"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]
相关文章推荐
- 扩展和嵌入Python 解释器(Extending and Embedding the Python Interpreter)--摘要
- Extending and Embedding the Python Interpreter¶
- Python常见问题(5):Python扩展与嵌入 Extending/Embedding FAQ
- Extending and Embedding PHP-扩展和移植PHP(七)
- Extending and Embedding PHP-扩展和移植PHP(八)
- Extending and Embedding PHP-扩展和移植PHP(三)
- Extending and Embedding PHP-扩展和移植PHP(一)
- Extending and Embedding PHP-扩展和移植PHP(四)
- Dreamweaver 扩展开发:C-level extensibility and the JavaScript interpreter
- Extending and Embedding PHP-扩展和移植PHP(二)
- Extending and Embedding PHP-扩展和移植PHP(五)
- 扩展和嵌入python解释器 - 摘要
- 1.1.1 The Python Interpreter : Python解释器
- Extending(扩展)&Embeding(嵌入)python
- Extending and Embedding PHP-扩展和移植PHP(六)
- The differences between Python 2 and Python 3
- [ZT]C++ 扩展和嵌入 Python
- Overloading,overriding,and extending functions and events 重载,重写和扩展函数和事件
- SWIG and Python(用SWIG将C/C++封装为Python扩展模块)
- C++ 扩展和嵌入 Python