下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
LearningCythonExpandyourexistinglegacyapplicationsinCusingPythonPhilipBIRMINGHAM-LearningCythonCopyright©2013Packt .Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.ProductionReference:PublishedbyPacktPublishing LiveryPlace35LiveryStreetBirminghamB32PB,UK.ISBN978-1-78328-079-www.packtpub.cCoverImagebySureshMogre(suresh.mogre.99@PhilipNamitKewatAntonyCommissioningmmedHardikB.CopySayaneeMukherjeeAdityaNairKirtiPaiAdithiShetty
ProjectRomalPaulRekhaNairSheetalProductionKirteeCoverKirtee欢迎加Python欢迎加Python编程学习交,群里免费提供500+本Python书籍AboutthePhilipHerronisanavidsoftwareengineerwhofocuseshispassiontowardscompilersandvirtualmachineimplementations.WhenhewasacceptedtoSummerofCode2010,heusedinspirationfromPaulBiggar'sPhDonoptimizationofdynamiclanguagestodevelopaproofofconceptGCCfrontendtocompilePython.ThisprojectsparkedhisdeepinterestofhowPythonAftercompletingaconsecutiveyearonthesameprojectin2011,PhilipdecidedtoapplyforCythonunderthePythonfoundationtogainadeeperappreciationofthestandardPythonimplementation.Throughthis,hestartedleveragingtheadvantagesofPythontocontrolthelogicinsystemsoreventoaddmorehigh-levelinterfacessuchasembeddinistedwebserversforRESTcallstoasystem-levelpieceofsoftwarewithoutwritinganyCcode.CurrentlyPhilipisemployedbyNYSEEuronextinBelfastNorthernIreland,workingonmultiprocessingsystems.ButhespendshiseveningshackingonG Cython,andGCC.Inthepast,hehasworkedwithWANdiscoasanApacheHadoopdeveloperandasaninternwithSAPResearchoncloudcomputing.Toachievethisbook,Iwouldliketothankmanypeople. mygirlfriendKirstyJohnstonforputtingupwithmylatenightsandgivingmetheconfidenceIneeded;you'rethebest!Mymumanddad,TrevorandAnnHerron,whohavealwayssupportedmemywholelife;thanksforhelmesomuch.IfeelthatIanLanceTaylorfrommyGCCSummerofCodeexperiencedeservesaspecialmention;ifitwasn'tforyou,Iwouldn'tbewritinganythinglikethisrightnow;youhaveshownmehowtoprojecteventhoughIhadalotgoingonatthetime;youhelpedmegetitdoneandpassed;youtaughtmehowtomanagetime.SpecialthanksNicholasMarriottforhelmewiththeTmuxcodebase!IwouldalsoliketothankGordonHamilton,TrevorLorimer,TrevorThompson,andDrColinTurnerforthesupportyou'veallgivenme.AbouttheNamitKewatisafinancial ystandXBRLexpert.Athisjob,hehasworkedonalmostallthemajorSECfilers'XBRLcreation(forexample,BAC,GS,FB,andWSH).HeisusingPythonextensivelyforextractingandgeneratingreportsfromfinancialinformationpresentinXBRLfinancialreports.HehasmadeafewqualitycheckingappsinPythonthatareextensivelyusedbyhiscompanyforqualitychecks,whichreducesthequality-checktimefromhourstoGoranMilovanovicisaPythonprogrammerfromtheBlenderGameEnginecommunity.Hisinterestsincludereal-timesimulation,nanotechnology,andeducation.Ifheiswellknown,itwouldbeforhis tutorials,whichcanbefoundbyGooglingfor"Goran'sPythontutorialIwouldliketothankmymotherandfatherfortheircontinuingsupportandencouragement.Supportfiles,eBooks,discountoffersandYoumightwanttovisitwww.PacktPforsupportfilesanddownloadsrelatedtoyourbook.DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusatservice@formoredetails.Atwww.PacktP,youc soreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.http://PacktLib.PacktPub.cDoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt'sonlinedigitalbooklibrary.Here,youcanaccess,readandsearchacrossPack libraryofbooks.WhyFullysearchableacrosseverybookpublishedbyCopyandpaste,printandbookmarkOndemandandaccessibleviawebFreeAccessforPacktaccountIfyouhaveanaccountwithPacktatwww.PacktP,youcanusethistoaccessPacktLibtodayandviewnineentirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.Tableof Chapter1:CythonWon't Whatthisbook Whatthisbook Installing Theemacs Gettingthecode o Moduleonyour CallingintoyourC Type Chapter2:Understanding Linking Thepublic Logginginto Python Cythoncdefsyntaxandusage Typedefandfunction Scalableasynchronous Csocketswith Whatis Messaging Cython Cython 欢迎加Python欢迎加Python编程学习交,群里免费提供500+本Python书籍TableofPythonmessaging Integrationwithbuild Python Chapter3:Extending CythonpurePython Python Pythongarbage Extending Tmuxbuild Embedding ImplementingaTmux CompilingpurePython Chapter4:Debugging UsingGDBonyour Running GeneralCython Type No* Pythonexceptionsin ForloopsonC Bool NoC MultipleCython Initializing CallingintopurePython Keecallstackssmalland Chapter5:Advanced C++ C++newkeywordand Bool TableofStaticclassmemberCaveatonC++CallinginCandC++PythonPythonthreadingandAtomicMessagingserverMoreMessagingserverworkingwithPythonIRCUnittestingthenativePreventingCythontyviaParsinglargeamountsofChapter6:FurtherOpenMPObjectCompilePythonUsingPyrexversusSWIGversusCythonandNumbaversusParakeetandGyPythonfrontendtoLinksandfurtherCythonisatoolthatmakeswritingCextensionstoPythonaseasyaswritingPythonitself.ThisistheslogantowhichCythonconforms.Forthosewhodon'tknowwhatIamtalkingabout,writingCextensionstoPythonfromscratchisafairlydifficultprocess;unlessyoureallyunderstandthePython-CAPIfullywithrespecttoGILandgarbagecollectionaswellasmanagingyourownreferencecounting,it'saverydifficultprocess.ItendtoconsiderCythontobealongtheselines:whatJythonistoJavaandPython,CythonistoC/C++andPython.Itallowsustoextendanddevelopbindingstoapplicationsinareallyintuitivemannersothatweareabletoreusecodefromlevelsofthesoftwarestack.TheCythoncompilercompilestheCythonlanguageorevenpurePythontoanativeCPythonmodule,whichcanbeloadedlikeanyPythonmoduleviathenormalimport.Itnotonlygeneratesallthewrapperandboilerplatecode,butalsocommandsthePythongarbagecollectortoaddallthenecessaryreferencecountingcode.What'sinterestingwiththeCythonlanguageisthatithasnativesupportforunderstandingCtypesandisabletojugglethemfrombothlanguages.It'ssimplyanextensionofPythonthathasadditional andsomemoreconstructsandwhichallowsyoutocallintoCorPython.WhatthisbookChapter1,CythonWon'tBite,willgiveyouanintroductiontowhatCythonisandhowitworks.Itcoverssettingupyourenvironmentandrunningthe oWorld"application.Chapter2,UnderstandingCython,willstarttogetseriouswithCythonandwilldiscusshowtodescribeCdeclarationswithrespecttoCythonalongwithcallingconventionsandtypeconversion.Chapter3,ExtendingApplications,willwalkyouthroughcomparingtheexecutionofpurePythoncodewiththeCythonversionofthesamecode.WealsolookatextendingTmux,apureCproject,withCython.Chapter4,DebuggingCython,willcoverhowtouseGDBtodebugyourcodetherelativeGDBcommands.Thereisalsoanextensivesectiononcaveatsandthingstobeawareofaswellasconventions.Chapter5,AdvancedCython,willcovertheusageofC++withCython,whichisjustaseasyasusingCwithCython.WewillalsoworkthroughallthesyntaxnecessarytowrapC++.Wewillthenlookintothecaveatsandmoreonoptimizations,comparingaPythonXMLparserwithaCythonXMLparseronlargeXMLfiles.Chapter6,FurtherReading,wrapsupthebookwithafinallookatsomeandconventions.Then,wecompareCythonagainstothersimilartoolslikeNumbaandSWIG,andwewilldiscusshowitsusedinNumPyandhowwecanusePyPyandPython3.WhatyouneedforthisForthisbook,IusedmyMacBookandanUbuntuvirtualmachine(GDBistoooldonMacOSXfordebugging).YouwillrequirethefollowingonMacOSX:PythonPythonOnUbuntu,youcaninstallmostcomponentsviathe$sudoapt-getinstallbuild-essentialgdbcytOfcourse,Iwillgooverthisintheintroduction,butaslongasyouhaveaCcompilerandPythonandhavePythonheadersinstalled,youwillhaveeverythingyouneedforCython.WhothisbookisThisbookisintendedforCdeveloperswholikeusingPythonandPythonuserswantingtoimplementnativeC/C++extensionstoPython.Asareader,youcanexpecttobeshownhowyoucandevelopapplicationswithCython,withanemphasisonextendingexistingsystemswithhelponhowyoucanapproachlow-levelsystemdaemonsthatwecould andextendthemandinteractwithcodealone!ThismodelofdevelopmentcanprovetobeefficientandofgreatreturntoItalsoallowsformuorerapiddevelopmentofthestateorlogicinasystem.ThereisnoneedtoworryaboutlongdonversionalgorithmsinCforngsmallthingsandthenneedingtochangeitallagain.Inthisbook,youwillfindanumberofstylesoftextthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestyles,andanexplanationoftheirmeaning.Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andhandlesareshownasfollows:"Butnotethatyoucannotusedelonthisinstanceelseyouwillgetanerror."Ablockofcodeissetas#ifndef#defin
namespacemynamesp{voidmyFunc(void)classmyCla{publicintxvoidprintMe(void)}}#endif Whenwewishtodrawyourattentiontoaparticularpartofacodeblock,therelevantlinesoritemsaresetinbold:#ifndef#defin
namespacemynamespacevoidmyFunc(void)classmyClasspublicintxvoidprintMe(void)}}#endif Anycommand-lineinputoroutputiswrittenasphilips-macbook:primesredbrain$cythonpyprimes.py–philips-macbook:primesredbrain$gcc-g-O2pyprimes.c-opyprime`python-config--includes–libsWarningsorimportantnotesappearinaboxlikethis.Tipsandtricksappearlikethis.ReaderFeedbackfromourreadersisalways e.Letusknowwhatyouthinkaboutthisbook—whatyoulikedormayhavedisliked.Readerfeedbackisimportantforustodeveloptitlesthatyoureallygetthemostoutof.Tosendusgeneralfeedback,simplysendan tofeedback@,andmentionthebooktitleviathesubjectofyourmessage.Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,/authors.CustomerNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.DownloadingtheexampleYoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountat.Ifyoupurchasedthisbookelsewhere,youcanvisit/supportandregistertohavethefiles eddirectlytoyou.Althoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—wewouldbegratefulifyouwouldreportthistous.Byngso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisiting/submit-errata,selectingyourbook,clickingontheerratasubmissionformwillbeacceptedandtheerratawillbeuploadedonourwebsite,oraddedtoanylistofexistingerrata,undertheErratasectionofthattitle.Anyexistingerranbeviewedbyselectingyourtitlefrom/support.PiracyofcopyrightmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucomeacrossanyillegalcopiesofourworks,inanyform,ontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediaysothatwecanpursuearemedy.Pleasecontactusatcopyright@withalinktotheedpiratedmaterial.Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyouvaluablecontent.Youcancontactusatquestions@ifyouarehavingaproblemwithanyaspectofthebook,andwewilldoourbesttoaddressit.CythonWon'tCythonmakeswritingCextensionsforPythonaseasyasPythonitself.ItsmainusewithinthecommunityistheMathematicssoftwarepackage,SAGE,whichisusedtoperformfastandscalablecalculations.Mostnotably,itprovidesasafeandmaintainablewayofbuildingnativemodulesforPythonviaautogenerationoftherequiredcode.ally,IhaveusedCythontotakecontroloflegacyapplicationswherethesystemhasbeenimplementedinC/C++andinwhichaddingfunctionalityepainful;wecanthenuseittogeneratebindingssothatthenativeapplicationandthePythononecanworktogether!Withthis,youareabletoperformhigh-levellogicwithinPythonbutleveragethepowerofyournativesystem.WhatthisbookPythonhas eagreatexceptioninsoftwareengineeringinthelastfewyears;itcanbeusedinanywayyoucanthinkoftocreateorextendsoftwaresystemswithlowcostinregardstodevelopmenttime.Wecsouseittoextendsoftwarerangingfromsystem-leveldistributedsystemstohigh-levelwebapplications.ThisbookwilldemonstratehowtogainmorefromPython.Incaseyou'renotaware,PythoncanbeextendedvianativeC/C++codeusingextensionmodulesoverPyObjectorbyusingCtypes.ngthismanuallyisgenerallynotagoodidea,asyoureallyneedtoknowhowPythonworksinternally.Forexample,youneedtoknowaboutgarbagecollectionsoyourPythonobjectsdon'tgetcollected.ButthisiswhereCythoncomesin;itwillgeneratealloftheCPythonAPIwrappercodenecessaryandcorrectly.CythonWon'tWhatthisbookIt'sgoodtobeclearthatinthisbook,IwillassumeyouhaveexperienceandknowledgeofCandPython,butmoreimportantly,youshouldbecomfortablewiththeCcompilationandlinkingprocesstocreatesharedlibrariesandexecutables.ThisisimportanttogetthemostoutofCythonbecausetheexamplesseenontheInternetgenerallydealwithverysmallsingleCythonfileprojects,andthosearen'tthathelpfulformostofus.IhopethatafterreadingthisbookyouwillbecomfortablewithCython.Theonline ationwillprovideallthereferencesyouwillneed.InstallingNowlet'sgetCythoninstalled.ThinkofCythonasatoollikeBison,flex,orGCC;ittakesaninputsourceandgeneratesanotherthatyoucompileandlink:Fedora–Fedoracomeswiththeyumpackagemanager.So,youcansimplyrunyuminstallCython.Ubuntu/Debian–AswithFedora,Ubuntuhasapackageavailableviaaptitude:apt-getinstallCython.Mac–InstallXcodeandthecommand-linetools.Then,runthe$curl-O/release/Cython-0.18.tar.g$tarzxvfCython-0.18.tar.g$cdCython-0.$sudopythonsetup.pyinstaWindows–Althoughthereareaplethoraofoptionsavailable,followingthiswikiisthesafestoptiontostayuptodate:http://wiki./InstallingOnWindows.TheemacsThereisanemacsmodeforCythonavailable,asthePythonemacsmodedoesn'tworkcorrectly.So,youcanaddtheTools/cython-mode.elmodetoyour~/.emacs.ddirectoryandthenaddrequiretoyour~/.emacs(add-to-lis 'load-path"~/.emacs.d/"(requi 'cython-modeGettingthecode
ChapterThroughoutthisbook,IintendtoshowrealexamplesthatareeasytodigesttohelpyougetafeelofthedifferentthingsyoucanachievewithCython.Toaccessanddownloadthecodeusedintheseexamples,visit atthefollowinglink:$gitclonegit://.com/redbrain/cython-book.gioHopefullybynowyou'vegotCythondownandcompiledandinstalledit.Let'scheckthisbyrunningthefollowingcommand:$cython--versiLet'sdoasanitytestandrunthetypical oWorld"redbrain@gamma:~/workspace/cython-book/chapter1 oworld$WehavenowcreatedtheCython oworld.somodule!YoucanseeitwithinPython(makesureyouareinthesamedirectoryasthe oworld.somodule):redbrain@gamma:~/workspace/cython-book/chapter1/ oworld$pythonPython2.7.3(default,Aug 12012,05:16:07)[GCC4.6.3]onliType"help","copyright","credits"or"license"formoreinformation>>>impor oworloWorldfromcythonWeimport oworldsincethismoduleisnowavalidPythonmodulethatcanbeloaded.And,onimporting,wedeclaredtheCythoncodetosimplyprintourmessage.Notveryexciting,butthat'showthe" oWorld"moduleis.Let'slookatwhatwedid;Cythonfileshavetheextensions.pyxand.pxd.Fornow,allwewillcareaboutarethe.pyxfiles.Laterinthisbook,Iwillintroducetheuseof.pxdandwhatyoucanusethisfor.Forpurposesofclarity,it'sgoodtounderstandthebasicpipelineofwhat'sgoingontogeneratethis oworld.somoduleforPython.Cythonworksinthesamewayasanyothercodegenerator.CythonWon'tTheflowdepictedinthefollowingfigureillustrateshowCythonIwroteabasicMakefilesoyoucansimplyrunmaketocompiletheseexamples.Itusesthesetup.pystyletoletPythonhandlecompilingandsettingupthesemodules.Here'sthecodetodothismanually:$cyt oworld.$gcc-g-O2-fpic`python-config--cflags`-c oworld.c-ooworld.o$gcc-shared- oworld.s oworld.o`python-config--libsIfeelthisisaveryimportantskilltolearnwithCdevelopmentbecauseyouwillstartthinkingofyourcodeintermsofhowyoucanshareitmoreeasily.ModuleonyourNowthatyou'veseenthe" oWorld"module,let'sseehowyoucanwriteyourownmoduletodosomething!Then,youcanlinkitagainstsomeofyourowncode.Later,we'llintroducetheideaofwrapyourcode.CallingintoyourCCythonisasupersetofPython.Althoughthesyntaxand willworkinthesameway,weshouldbecarefulwhentalkingaboutPythonandCythonforclarity.ToseeCythoninaction,let'sbuilda o-world-stylemodulebutperformsomethingbasic,justtobesureweareonthesamepage.Openafilecalledmycode.candinsertthefollowingcodeinto#include<myfunc(inta intb{printf("lookwearewithinyourccode!!\n");returna+b;}ChapterThisistheCcodewewillcall—justasimplefunctiontoaddtwointegersyou'veprobablyseenbefore.Nowlet'sgetPythontocallit.Openafilecalledmycode.h,whereinwewilldeclareourprototypesforCythonasfollows:#ifndef#defin
externintmyfunc(int,int);#endif// WeneedthissothatCythoncanseetheprototypeforthefunctionwewanttocall.Inpractice,youwillalreadyhaveyourheadersinyourownprojectwithyourprototypesanddeclarations.Openafilecalledmycodecpy.pyxandinsertthefollowingcodeintocdefexternfrom"mycode.h"cdefintmyfunc(int,intdefcallCfunc()printmyfunc(1,2WithinthisCythoncode,weinitiallyhavetodeclarewhatCcodewecarecdefisakeywordsignifyingthatthisisfromtheCcodethatwillbelinkedNowthatwehavedeclaredtheheaderwiththeprototypetosquashanyundeclaredfunctionwarningsfromourcompiler,wecanmakeawrapperfunction.Atthispoint,wewillspecifyhowPythonwillcallthisnativecode,sincecallingdirectlyintoCcodeisdangerous.Therefore,Cythonhandlesalltype-conversionproblemsforus.Abasicwrapperfunction,callCfunc,isallweneed—itcallsthemyfuncfunctionandpassestheintegers1and2;thenitsimplyprintstheresult.Tocompilethis,usethe$cythonmycodecpy.$gcc-g-O2-fpic-cmycode.c-omycode.$gcc-g-O2-fpic-cmycodecpy.c-omycodecpy`python-config--cflags$gcc-shared-omycodecpy.somycode.omycodecpy.o`python-config--libsCythonWon'tWehavetoremembertolinkinthecodethathastheCfunction;inthismycode.c.Ifyou'renotfamiliarwithwhatImeanhere,youmayneedtorevisitsomeCtutorialsoncompilation,aseveryCfileiscompiledtoanobjectfileandthenwelinkallobjectfilesintoabinary.Therefore,youneedtobesureyoulinkinallnecessaryobjectfiles.redbrain@gamma:~/workspace/cython-book/chapter1/ownmodule$pythonPython2.7.3(default,Aug 12012,05:16:07)[GCC4.6.3]onliType"help","copyright","credits"or"license"formoreinformation>>>frommycodepyimportcallCf>>>callCfunclookwearewithinyourccode!!So,wehavenowcompiledandcalledournativecodefromPythoncode.Ihopethislinkingagainstsomenativelibraries,makingbindingstosuchlibrariesverysimple.YoumighthavenoticedthatwecalledaCythonfunctiondirectlywithnoarguments,whichinturncalledourC(thecdefprototype)functionwithtwointegerarguments.WhatifwewantedtheCythoncodetohandlearguments?Wecouldexecutethefollowing:defcallCfunc2(intx,inty):printmyfunc(x,y)WehavenowaddedtheintargumentstothePythonwrapperfunctionwedefined.ThiswillrequirePythoncodetobetype-safeandtoconvertPyObjectstoCtypesforusautomatically.WhenyoucreateanintegerPythonobject,thetypeisnotinteger,it'sPyObject.IfyouwanttousethisinC,youneedtogetthedataviathePythonCAPI,butCythonwilldothisforusautomatically.Forexample,ifyoupassillegalarguments,youwillgetthefollowing:>>>importmyc>>>mycodepy.callCfunc2(1,'string')Traceback(mostrecentcalllast):File"<stdin>" line1 in<modulFile"mycodepy.pyx", line7, inmycodepy.callCfunc2(mycodepy.c:733)defcallCfunc2(intx,inty):TypeError:aninteg isrequiChapterEvenifyousimplyaddmoretypesafetytoyourPythoncodeviatheuseofCtypesfromCython,youwillfindthatyougainabitofspeedandsomenicecode.ThisisbecausetheCythoncompilercanoptimizemu oreaggressivelytoavoidusingPythoncalls.DownloadingtheexampleYoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.PacktP.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.PacktP/supportandregistertohavethefiles eddirectlytoyou.Right,soIknowthisisn'tthemostexcitingthingyou'veeverdone,butifyoucouldjusttakeastepbackandconsiderthis:purePythoncodecallingintoCcodedirectly!Thinkwhatyoucoulddowithit—it'sprettyexciting!Inthenextchapter,Iwillshowyoumoreoncdefandthe arounditandhowtoshareyourCythonfunctionssothattheyarecallablefromCcode.Withthis,anythingcancallanything!Notonlythat,wecanlookathowwecompileournormalPythoncodeand littousesomeCtypestotryandgetsomemoreefficiencybylookingintomoresyntaxandmorewaystouseCython.UnderstandingIfyouweretocreateanAPIforPython,youshouldwriteitusingCythontocreateamoretype-safePythonAPI.Or,youcouldtaketheCtypesfromCythontoimplementthesamealgorithmsinyourPythoncode,andtheywillbefasterbecauseyou'respecifyingthetypesandyouavoidalotofthetypeconversionrequired.ConsideryouareimplementingafreshprojectinC.Thereareafewissueswealwayscomeacrossinstartingfresh;forexample,choosingtheloggingorconfigurationsystemwewilluseorimplement.WithCython,wecanreusethePythonloggingsystemaswellastheConfigParserstandardlibrariesfromPythoninourCcodetogetaheadstart.Ifthisdoesn'tprovetobethecorrectsolution,wecanchopandchangeeasily.WecanevenextendandgetPythontohandleallgetoptusage.SincethePythonAPIisverypowerful,wemightaswellmakePythondoasmuchasitcantogetusofftheground.AnotherquestionisdowewantPythonbeour"driver"(mainentryfunction)ordowewanttohandlethisfromourCcode?CythonInthenexttwoexamples,IwilldemonstratehowwecanreusethePythonloggingandPythonConfigParsermodulesdirectlyfromCcode.Butthereareafewformalitiestogetover,namelythePythoninitializationAPIandthelinkloadmodelforfullyembeddedPythonapplicationsforusingthesharedlibrarymethodusedinChapter1,CythonWon'tBite.It'sverysimpletoembedPythonwithinaC/C++application;youwillrequirethefollowingboilerplate:#include<Pytmain(intargc,char**argvUnderstanding{Py_SetProgramName(argv[0]);Py_Initialize();/*Doallyourstu insidehere...*Py_Finali return0}MakesureyoualwaysputthePython.hheaderattheverybeginningofeachCfile,becausePythoncontainsalotofheadersdefinedforsystemheaderstoturnthingsonandofftomakethingsbehavecorrectlyonyoursystem.Later,IwillintroducesomeimportantconceptsabouttheGILthatyoushouldknowandtherelevantPythonAPIcodeyouwillneedtousefromtimetotime.Butfornow,thesefewcallswillbeenoughforyoutogetofftheground.LinkingLinkingmodelsareextremelyimportantwhenconsideringhowwecanextendorembedthingsin
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 《AutoCAD机械绘图》课程标准
- 洛阳市吉利区2025届三年级数学下学期期末学业质量监测试题含答案
- 2026年10月自考劳动法(00167)模拟试卷(含答案解析)
- 重冶湿法冶炼工岗前技能安全考核试卷含答案
- 煤提质工发展趋势强化考核试卷含答案
- 微波通信机务员安全知识竞赛测试考核试卷含答案
- 钎焊材料冶炼成型工岗前技能安全考核试卷含答案
- 纸张、书画文物修复师岗中诚信道德考核试卷含答案
- 潜水员创新意识评优考核试卷含答案
- 保温材料原料工班组建设强化考核试卷含答案
- 2026年七年级数学竞赛试题及答案
- 昭通市2026年市直事业单位公开选调工作人员(42人)笔试参考题库及答案解析
- 小学六年级少先队建队日活动方案课件
- ISO9001-2026《质量管理体系-要求》正文与附录整合版(雷泽佳编辑-2026年9月)
- 重症医学科进修汇报
- 工厂电气设备点检标准规程
- 2025年下半年安徽交控驿达集团招聘3人笔试历年参考题库附带答案详解
- 山东青岛华通国有资本投资运营集团有限公司招聘笔试真题2025
- 2026年土木工程力学练习题大全
- 阿里地区古象雄环线沿线保护区外旅游基础设施建设项目水土保持报告表
- 2026胸腔闭式引流护理团体标准
评论
0/150
提交评论