SWIG and Python.docx
《SWIG and Python.docx》由会员分享,可在线阅读,更多相关《SWIG and Python.docx(94页珍藏版)》请在冰豆网上搜索。
SWIGandPython
31SWIGandPython
∙Overview
∙Preliminaries
oRunningSWIG
oUsingdistutils
oHandcompilingadynamicmodule
oStaticlinking
oUsingyourmodule
oCompilationofC++extensions
oCompilingfor64-bitplatforms
oBuildingPythonExtensionsunderWindows
∙AtourofbasicC/C++wrapping
oModules
oFunctions
oGlobalvariables
oConstantsandenums
oPointers
oStructures
oC++classes
oC++inheritance
oPointers,references,values,andarrays
oC++overloadedfunctions
oC++operators
oC++namespaces
oC++templates
oC++SmartPointers
oC++ReferenceCountedObjects(ref/unref)
∙FurtherdetailsonthePythonclassinterface
oProxyclasses
oMemorymanagement
oPython2.2andclassicclasses
∙Crosslanguagepolymorphism
oEnablingdirectors
oDirectorclasses
oOwnershipandobjectdestruction
oExceptionunrolling
oOverheadandcodebloat
oTypemaps
oMiscellaneous
∙Commoncustomizationfeatures
oC/C++helperfunctions
oAddingadditionalPythoncode
oClassextensionwith%extend
oExceptionhandlingwith%exception
∙Tipsandtechniques
oInputandoutputparameters
oSimplepointers
oUnboundedCArrays
oStringhandling
oArrays
oStringarrays
oSTLwrappers
∙Typemaps
oWhatisatypemap?
oPythontypemaps
oTypemapvariables
oUsefulPythonFunctions
∙TypemapExamples
oConvertingPythonlisttoachar**
oExpandingaPythonobjectintomultiplearguments
oUsingtypemapstoreturnarguments
oMappingPythontuplesintosmallarrays
oMappingsequencestoCarrays
oPointerhandling
∙DocstringFeatures
oModuledocstring
o%feature("autodoc")
▪%feature("autodoc","0")
▪%feature("autodoc","1")
▪%feature("autodoc","docstring")
o%feature("docstring")
∙PythonPackages
∙Python3Support
oFunctionannotation
oBufferinterface
oAbstractbaseclasses
Caution:
Thischapterisunderrepair!
ThischapterdescribesSWIG'ssupportofPython.SWIGiscompatiblewithmostrecentPythonversionsincludingPython3.0andPython2.6,aswellasolderversionsdatingbacktoPython2.0.Forthebestresults,considerusingPython2.3ornewer.
ThischaptercoversmostSWIGfeatures,butcertainlow-leveldetailsarecoveredinlessdepththaninearlierchapters.Attheveryleast,makesureyoureadthe"SWIGBasics"chapter.
31.1Overview
TobuildPythonextensionmodules,SWIGusesalayeredapproachinwhichpartsoftheextensionmodulearedefinedinCandotherpartsaredefinedinPython.TheClayercontainslow-levelwrapperswhereasPythoncodeisusedtodefinehigh-levelfeatures.
Thislayeredapproachrecognizesthefactthatcertainaspectsofextensionbuildingarebetteraccomplishedineachlanguage(insteadoftryingtodoeverythinginCorC++).Furthermore,bygeneratingcodeinbothlanguages,yougetalotmoreflexibilitysinceyoucanenhancetheextensionmodulewithsupportcodeineitherlanguage.
IndescribingthePythoninterface,thischapterstartsbycoveringthebasicsofconfiguration,compiling,andinstallingPythonmodules.Next,thePythoninterfacetocommonCandC++programmingfeaturesisdescribed.Advancedcustomizationfeaturessuchastypemapsarethendescribedfollowedbyadiscussionoflow-levelimplementationdetails.
31.2Preliminaries
31.2.1RunningSWIG
SupposethatyoudefinedaSWIGmodulesuchasthefollowing:
/*File:
example.i*/
%moduleexample
%{
#defineSWIG_FILE_WITH_INIT
#include"example.h"
%}
intfact(intn);
The #defineSWIG_FILE_WITH_INIT lineinsertsamacrothatspecifiesthattheresultingCfileshouldbebuiltasapythonextension,insertingthemodule init code.This .i filewrapsthefollowingsimpleCfile:
/*File:
example.c*/
#include"example.h"
intfact(intn){
if(n<0){/*Thisshouldprobablyreturnanerror,butthisissimpler*/
return0;
}
if(n==0){
return1;
}
else{
/*testingforoverflowwouldbeagoodideahere*/
returnn*fact(n-1);
}
}
Withtheheaderfile:
/*File:
example.h*/
intfact(intn);
TobuildaPythonmodule,runSWIGusingthe -python option:
$swig-pythonexample.i
IfbuildingaC++extension,addthe -c++ option:
$swig-c++-pythonexample.i
Thiscreatestwodifferentfiles;aC/C++sourcefile example_wrap.c or example_wrap.cxx andaPythonsourcefile example.py.ThegeneratedCsourcefilecontainsthelow-levelwrappersthatneedtobecompiledandlinkedwiththerestofyourC/C++applicationtocreateanextensionmodule.ThePythonsourcefilecontainshigh-levelsupportcode.Thisisthefilethatyouwillimporttousethemodule.
Thenameofthewrapperfileisderivedfromthenameoftheinputfile.Forexample,iftheinputfileis example.i,thenameofthewrapperfileis example_wrap.c.Tochangethis,youcanusethe -o option.ThenameofthePythonfileisderivedfromthemodulenamespecifiedwith%module.Ifthemodulenameis example,thenafile example.py iscreated.
Thefollowingsectionshavefurtherpracticalexamplesanddetailsonhowyoumightgoaboutcompilingandusingthegeneratedfiles.
31.2.2Usingdistutils
Thepreferredapproachtobuildinganextensionmoduleforpythonistocompileitwithdistutils,whichcomeswithallrecentversionsofpython(DistutilsDocs).
Distutilstakescareofmakingsurethatyourextensionisbuiltwithallthecorrectflags,headers,etc.fortheversionofPythonitisrunwith.DistutilswillcompileyourextensionintoasharedobjectfileorDLL(.so onLinux, .pyd onWindows,etc).Inaddition,distutilscanhandleinstallingyourpackageintosite-packages,ifthatisdesired.Aconfigurationfile(conventionallycalled:
setup.py)describestheextension(andrelatedpythonmodules).Thedistutilswillthengeneratealltherightcompilerdirectivestobuilditforyou.
Hereisasample setup.py filefortheaboveexample:
#!
/usr/bin/envpython
"""
setup.pyfileforSWIGexample
"""
fromdistutils.coreimportsetup,Extension
example_module=Extension('_example',
sources=['example_wrap.c','example.c'],
)
setup(name='example',
version='0.1',
author="SWIGDocs",
description="""Simpleswigexamplefromdocs""",
ext_modules=[example_module],
py_modules=["example"],
)
Inthisexample,theline:
example_module=Extension(....) createsanExtensionmoduleobject,definingthenameas _example,andusingthesourcecodefiles:
example_wrap.c,generatedbyswig,and example.c,youroriginalcsource.Theswig(andotherpythonextensionmodules)traditionisforthecompiledextensiontohavethenameofthepythonportion,prefixedbyanunderscore.Ifthenameofyourpythonmoduleis"example.py",thenthenameofthecorrespondingobjectfilewillbe"_example.so"
The setup callthensetsupdistutilstobuildyourpackage,definingsomemetadata,andpassinginyourextensionmoduleobject.Oncethisissavedas setup.py,youcanbuildyourextensionwiththesecommands:
$swig-pythonexample.i
$pythonsetup.pybuild_ext--inplace
Anda.so,or.pydor...willbecreatedforyou.Itwillbuildaversionthatmatchesthepythonthatyourunthecommandwith.Takingapartthecommandline:
∙python --theversionofpythonyouwanttobuildfor
∙setup.py --thenameofyoursetupscript(itcanbecalledanything,butsetup.pyisthetradition)
∙build_ext --tellingdistutilstobuildextensions
∙--inplace --thistellsdistutilstoputtheextensionlibinthecurrentdir.Otherwise,itwillputitinsideabuildhierarchy,andyou'dhavetomoveittouseit.
Thedistutilshavemanyotherfeatures,consultthepythondistutilsdocsfordetails.
Thissameapproachworksonallplatformsiftheappropriatecompilerisinstalled.(itcanevenbuildextensionstothestandardWindowsPythonusingMingGW)
31.2.3Handcompilingadynamicmodule
Whilethepreferredapproachtobuildinganextensionmoduleistousethedistutils,somepeopleliketointegratebuildingextensionswithalargerbuildsystem,andthusmaywishtocompiletheirmoduleswithoutthedistutils.Todothis,youneedtocompileyourprogramusingcommandslikethis(shownforLinux):
$swig-pythonexample.i
$gcc-O2-fPIC-cexample.c
$gcc-O2-fPIC-cexample_wrap.c-I/usr/local/include/python2.5
$gcc-sharedexample.oexample_wrap.o-o_example.so
Theexactcommandsfordoingthisvaryfromplatformtoplatform.However,SWIGtriestoguesstherightoptionswhenitisinstalled.Therefore,youmaywanttostartwithoneoftheexamplesinthe SWIG/Examples/python directory.Ifthatdoesn'twork,youwillneedtoreadtheman-pagesforyourcompilerandlinkertogettherightsetofoptions.Youmightalsocheckthe SWIGWiki foradditionalinformation.
Whenlinkingthemodule, thenameoftheoutputfilehastomatchthenameofthemoduleprefixedbyanunderscore.Ifthenameofyourmoduleis"example",thenthenameofthecorrespondingobjectfileshouldbe"_example.so"or"_examplemodule.so".Thenameofthemoduleisspecifiedusingthe %module directiveorthe -module commandlineoption.
CompatibilityNote:
InSWIG-1.3.13andearlierreleases,modulenamesdidnotincludetheleadingunderscore.ThisisbecausemoduleswerenormallycreatedasC-onlyextensionswithouttheextraPythonsupportfile(instead,creatingPythoncodewassupportedasanoptionalfeature).ThishasbeenchangedinSWIG-1.3.14andisconsistentwithotherPythonextensionmodules.Forexample,the socket moduleactuallyconsistsoftwofiles; socket.py and _socket.so.Manyotherbuilt-inPythonmodulesfollowasimilarconvention.
31.2.4Staticlinking
AnalternativeapproachtodynamiclinkingistorebuildthePythoninterpreterwithyourextensionmoduleaddedtoit.Inthepast,thisapproachwassometimesnecessary