SWIG and Python.docx

上传人:b****7 文档编号:26640154 上传时间:2023-06-21 格式:DOCX 页数:94 大小:58.96KB
下载 相关 举报
SWIG and Python.docx_第1页
第1页 / 共94页
SWIG and Python.docx_第2页
第2页 / 共94页
SWIG and Python.docx_第3页
第3页 / 共94页
SWIG and Python.docx_第4页
第4页 / 共94页
SWIG and Python.docx_第5页
第5页 / 共94页
点击查看更多>>
下载资源
资源描述

SWIG and Python.docx

《SWIG and Python.docx》由会员分享,可在线阅读,更多相关《SWIG and Python.docx(94页珍藏版)》请在冰豆网上搜索。

SWIG and Python.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 初中教育 > 英语

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1