下載本文檔
版權(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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 湖鹽脫水工崗前節(jié)能考核試卷含答案
- 棕草編織工安全文明模擬考核試卷含答案
- 筒并搖工班組協(xié)作能力考核試卷含答案
- 汽車涂裝生產(chǎn)線操作工安全檢查強(qiáng)化考核試卷含答案
- 梅乙艾知識(shí)培訓(xùn)
- 海關(guān)行政處罰培訓(xùn)
- 酒店員工請(qǐng)假與出差制度
- 酒店客用物品損壞賠償制度
- 財(cái)務(wù)合同管理與審查制度
- 食品購(gòu)銷合同模板
- 農(nóng)民土地置換協(xié)議書
- 《化肥產(chǎn)品生產(chǎn)許可證實(shí)施細(xì)則(一)》(復(fù)肥產(chǎn)品部分)
- 多元香料配比優(yōu)化-洞察與解讀
- 零碳園區(qū)數(shù)字化建筑設(shè)計(jì)方案
- 不動(dòng)產(chǎn)數(shù)據(jù)整合技術(shù)策略規(guī)劃方案
- GB/T 46607.1-2025塑料熱固性粉末模塑料(PMCs)試樣的制備第1部分:一般原理及多用途試樣的制備
- 紫金礦業(yè)招聘面試題及答案
- 多功能工程機(jī)械故障診斷平臺(tái)創(chuàng)新創(chuàng)業(yè)項(xiàng)目商業(yè)計(jì)劃書
- 實(shí)施指南(2025)《HGT 5987-2021 硫酸行業(yè)綠色工廠評(píng)價(jià)要求》
- 2025至2030寵物衣服市場(chǎng)行業(yè)運(yùn)營(yíng)態(tài)勢(shì)與投資前景調(diào)查研究報(bào)告
- 2025至2030狂犬病疫苗行業(yè)發(fā)展研究與產(chǎn)業(yè)戰(zhàn)略規(guī)劃分析評(píng)估報(bào)告
評(píng)論
0/150
提交評(píng)論