python中文匯總-英文learning cython programming by philip herron_第1頁
python中文匯總-英文learning cython programming by philip herron_第2頁
python中文匯總-英文learning cython programming by philip herron_第3頁
python中文匯總-英文learning cython programming by philip herron_第4頁
python中文匯總-英文learning cython programming by philip herron_第5頁
免費(fèi)預(yù)覽已結(jié)束,剩余104頁可下載查看

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

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編程學(xué)習(xí)交,群里免費(fèi)提供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編程學(xué)習(xí)交,群里免費(fèi)提供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等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論