cffi-manual.texinfo 215 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139
  1. \input texinfo @c -*- Mode: Texinfo; Mode: auto-fill -*-
  2. @c %**start of header
  3. @setfilename cffi.info
  4. @settitle CFFI User Manual
  5. @exampleindent 2
  6. @c @documentencoding utf-8
  7. @c Style notes:
  8. @c
  9. @c * The reference section names and "See Also" list are roman, not
  10. @c @code. This is to follow the format of CLHS.
  11. @c
  12. @c * How it looks in HTML is the priority.
  13. @c ============================= Macros =============================
  14. @c The following macros are used throughout this manual.
  15. @macro Function {args}
  16. @defun \args\
  17. @end defun
  18. @end macro
  19. @macro Macro {args}
  20. @defmac \args\
  21. @end defmac
  22. @end macro
  23. @macro Accessor {args}
  24. @deffn {Accessor} \args\
  25. @end deffn
  26. @end macro
  27. @macro GenericFunction {args}
  28. @deffn {Generic Function} \args\
  29. @end deffn
  30. @end macro
  31. @macro ForeignType {args}
  32. @deftp {Foreign Type} \args\
  33. @end deftp
  34. @end macro
  35. @macro Variable {args}
  36. @defvr {Special Variable} \args\
  37. @end defvr
  38. @end macro
  39. @macro Condition {args}
  40. @deftp {Condition Type} \args\
  41. @end deftp
  42. @end macro
  43. @macro cffi
  44. @acronym{CFFI}
  45. @end macro
  46. @macro impnote {text}
  47. @quotation
  48. @strong{Implementor's note:} @emph{\text\}
  49. @end quotation
  50. @end macro
  51. @c Info "requires" that x-refs end in a period or comma, or ) in the
  52. @c case of @pxref. So the following implements that requirement for
  53. @c the "See also" subheadings that permeate this manual, but only in
  54. @c Info mode.
  55. @ifinfo
  56. @macro seealso {name}
  57. @ref{\name\}.
  58. @end macro
  59. @end ifinfo
  60. @ifnotinfo
  61. @alias seealso = ref
  62. @end ifnotinfo
  63. @c Typeset comments in roman font for the TeX output.
  64. @iftex
  65. @alias lispcmt = r
  66. @end iftex
  67. @ifnottex
  68. @alias lispcmt = asis
  69. @end ifnottex
  70. @alias res = result
  71. @c ============================= Macros =============================
  72. @c Show types, functions, and concepts in the same index.
  73. @syncodeindex tp cp
  74. @syncodeindex fn cp
  75. @copying
  76. Copyright @copyright{} 2005 James Bielman <jamesjb at jamesjb.com> @*
  77. Copyright @copyright{} 2005-2015 Lu@'{@dotless{i}}s Oliveira
  78. <loliveira at common-lisp.net> @*
  79. Copyright @copyright{} 2005-2006 Dan Knapp <danka at accela.net> @*
  80. Copyright @copyright{} 2005-2006 Emily Backes <lucca at accela.net> @*
  81. Copyright @copyright{} 2006 Stephen Compall <s11 at member.fsf.org>
  82. @quotation
  83. Permission is hereby granted, free of charge, to any person obtaining
  84. a copy of this software and associated documentation files (the
  85. ``Software''), to deal in the Software without restriction, including
  86. without limitation the rights to use, copy, modify, merge, publish,
  87. distribute, sublicense, and/or sell copies of the Software, and to
  88. permit persons to whom the Software is furnished to do so, subject to
  89. the following conditions:
  90. The above copyright notice and this permission notice shall be
  91. included in all copies or substantial portions of the Software.
  92. @sc{The software is provided ``as is'', without warranty of any kind,
  93. express or implied, including but not limited to the warranties of
  94. merchantability, fitness for a particular purpose and noninfringement.
  95. In no event shall the authors or copyright holders be liable for any
  96. claim, damages or other liability, whether in an action of contract,
  97. tort or otherwise, arising from, out of or in connection with the
  98. software or the use or other dealings in the software.}
  99. @end quotation
  100. @end copying
  101. @c %**end of header
  102. @dircategory Software development
  103. @direntry
  104. * CFFI Manual: (cffi-manual). CFFI Manual.
  105. @end direntry
  106. @titlepage
  107. @title CFFI User Manual
  108. @c @subtitle Version X.X
  109. @c @author James Bielman
  110. @page
  111. @vskip 0pt plus 1filll
  112. @insertcopying
  113. @end titlepage
  114. @contents
  115. @ifnottex
  116. @node Top, Introduction, (dir), (dir)
  117. @top cffi
  118. @insertcopying
  119. @end ifnottex
  120. @menu
  121. * Introduction:: What is CFFI?
  122. * Installation::
  123. * Implementation Support::
  124. * Tutorial:: Interactive intro to using CFFI.
  125. * Wrapper generators:: CFFI forms from munging C source code.
  126. * Foreign Types::
  127. * Pointers::
  128. * Strings::
  129. * Variables::
  130. * Functions::
  131. * Libraries::
  132. * Callbacks::
  133. * The Groveller::
  134. * Static Linking::
  135. * Limitations::
  136. * Platform-specific features:: Details about the underlying system.
  137. * Glossary:: List of CFFI-specific terms and meanings.
  138. * Comprehensive Index::
  139. @detailmenu
  140. --- Dictionary ---
  141. Foreign Types
  142. * convert-from-foreign:: Outside interface to backward type translator.
  143. * convert-to-foreign:: Outside interface to forward type translator.
  144. * defbitfield:: Defines a bitfield.
  145. * defcstruct:: Defines a C structure type.
  146. * defcunion:: Defines a C union type.
  147. * defctype:: Defines a foreign typedef.
  148. * defcenum:: Defines a C enumeration.
  149. * define-foreign-type:: Defines a foreign type specifier.
  150. * define-parse-method:: Specifies how a type should be parsed.
  151. @c * explain-foreign-slot-value:: <unimplemented>
  152. * foreign-bitfield-symbols:: Returns a list of symbols for a bitfield type.
  153. * foreign-bitfield-value:: Calculates a value for a bitfield type.
  154. * foreign-enum-keyword:: Finds a keyword in an enum type.
  155. * foreign-enum-value:: Finds a value in an enum type.
  156. * foreign-slot-names:: Returns a list of slot names in a foreign struct.
  157. * foreign-slot-offset:: Returns the offset of a slot in a foreign struct.
  158. * foreign-slot-pointer:: Returns a pointer to a slot in a foreign struct.
  159. * foreign-slot-value:: Returns the value of a slot in a foreign struct.
  160. * foreign-type-alignment:: Returns the alignment of a foreign type.
  161. * foreign-type-size:: Returns the size of a foreign type.
  162. * free-converted-object:: Outside interface to typed object deallocators.
  163. * free-translated-object:: Defines how to free a oreign object.
  164. * translate-from-foreign:: Defines a foreign-to-Lisp object translation.
  165. * translate-to-foreign:: Defines a Lisp-to-foreign object translation.
  166. * with-foreign-object:: Allocates a foreign object with dynamic extent.
  167. * with-foreign-objects:: Plural form of @code{with-foreign-object}.
  168. * with-foreign-slots:: Accesses the slots of a foreign structure.
  169. Pointers
  170. * foreign-free:: Deallocates memory.
  171. * foreign-alloc:: Allocates memory.
  172. * foreign-symbol-pointer:: Returns a pointer to a foreign symbol.
  173. * inc-pointer:: Increments the address held by a pointer.
  174. * incf-pointer:: Increments the pointer address in a place.
  175. * make-pointer:: Returns a pointer to a given address.
  176. * mem-aptr:: The pointer to an element of an array.
  177. * mem-aref:: Accesses the value of an index in an array.
  178. * mem-ref:: Dereferences a pointer.
  179. * null-pointer:: Returns a NULL pointer.
  180. * null-pointer-p:: Tests a pointer for NULL value.
  181. * pointerp:: Tests whether an object is a pointer or not.
  182. * pointer-address:: Returns the address pointed to by a pointer.
  183. * pointer-eq:: Tests if two pointers point to the same address.
  184. * with-foreign-pointer:: Allocates memory with dynamic extent.
  185. Strings
  186. * *default-foreign-encoding*:: Default encoding for the string types.
  187. * foreign-string-alloc:: Converts a Lisp string to a foreign string.
  188. * foreign-string-free:: Deallocates memory used by a foreign string.
  189. * foreign-string-to-lisp:: Converts a foreign string to a Lisp string.
  190. * lisp-string-to-foreign:: Copies a Lisp string into a foreign string.
  191. * with-foreign-string:: Allocates a foreign string with dynamic extent.
  192. * with-foreign-strings:: Plural form of @code{with-foreign-string}.
  193. * with-foreign-pointer-as-string:: Similar to CL's with-output-to-string.
  194. Variables
  195. * defcvar:: Defines a C global variable.
  196. * get-var-pointer:: Returns a pointer to a defined global variable.
  197. Functions
  198. * defcfun:: Defines a foreign function.
  199. * foreign-funcall:: Performs a call to a foreign function.
  200. * foreign-funcall-pointer:: Performs a call through a foreign pointer.
  201. * translate-camelcase-name:: Converts a camelCase foreign name to/from a Lisp name.
  202. * translate-name-from-foreign:: Converts a foreign name to a Lisp name.
  203. * translate-name-to-foreign:: Converts a Lisp name to a foreign name.
  204. * translate-underscore-separated-name:: Converts an underscore_separated foreign name to/from a Lisp name.
  205. Libraries
  206. * close-foreign-library:: Closes a foreign library.
  207. * *darwin-framework-directories*:: Search path for Darwin frameworks.
  208. * define-foreign-library:: Explain how to load a foreign library.
  209. * *foreign-library-directories*:: Search path for shared libraries.
  210. * load-foreign-library:: Load a foreign library.
  211. * load-foreign-library-error:: Signalled on failure of its namesake.
  212. @c * reload-foreign-libraries:: Reload foreign libraries.
  213. * use-foreign-library:: Load a foreign library when needed.
  214. Callbacks
  215. * callback:: Returns a pointer to a defined callback.
  216. * defcallback:: Defines a Lisp callback.
  217. * get-callback:: Returns a pointer to a defined callback.
  218. @end detailmenu
  219. @end menu
  220. @c ===================================================================
  221. @c CHAPTER: Introduction
  222. @node Introduction, Installation, Top, Top
  223. @chapter Introduction
  224. @cffi{} is the Common Foreign Function Interface for @acronym{ANSI}
  225. Common Lisp systems. By @dfn{foreign function} we mean a function
  226. written in another programming language and having different data and
  227. calling conventions than Common Lisp, namely, C. @cffi{} allows you
  228. to call foreign functions and access foreign variables, all without
  229. leaving the Lisp image.
  230. We consider this manual ever a work in progress. If you have
  231. difficulty with anything @cffi{}-specific presented in the manual,
  232. please contact @email{cffi-devel@@common-lisp.net,the developers} with
  233. details.
  234. @heading Motivation
  235. @xref{Tutorial-Comparison,, What makes Lisp different}, for
  236. an argument in favor of @acronym{FFI} in general.
  237. @cffi{}'s primary role in any image is to mediate between Lisp
  238. developers and the widely varying @acronym{FFI}s present in the
  239. various Lisp implementations it supports. With @cffi{}, you can
  240. define foreign function interfaces while still maintaining portability
  241. between implementations. It is not the first Common Lisp package with
  242. this objective; however, it is meant to be a more malleable framework
  243. than similar packages.
  244. @heading Design Philosophy
  245. @itemize
  246. @item
  247. Pointers do not carry around type information. Instead, type
  248. information is supplied when pointers are dereferenced.
  249. @item
  250. A type safe pointer interface can be developed on top of an
  251. untyped one. It is difficult to do the opposite.
  252. @item
  253. Functions are better than macros. When a macro could be used
  254. for performance, use a compiler-macro instead.
  255. @end itemize
  256. @c ===================================================================
  257. @c CHAPTER: Installation
  258. @node Installation, Implementation Support, Introduction, Top
  259. @chapter Installation
  260. @cffi{} can be obtained through one of the following means available
  261. through its @uref{http://common-lisp.net/project/cffi/,,website}:
  262. @itemize
  263. @item
  264. @uref{http://common-lisp.net/project/cffi/releases/?M=D,,official release
  265. tarballs}
  266. @item
  267. @uref{http://common-lisp.net/gitweb?p=projects/cffi/cffi.git,,git
  268. repository}
  269. @c snapshots have been disabled as of
  270. @c @item
  271. @c @uref{http://common-lisp.net/project/cffi/tarballs/?M=D,,nightly-generated
  272. @c snapshots}
  273. @end itemize
  274. In addition, you will need to obtain and install the following
  275. dependencies:
  276. @itemize
  277. @item
  278. @uref{http://common-lisp.net/project/babel/,,Babel}, a charset
  279. encoding/decoding library.
  280. @item
  281. @uref{http://common-lisp.net/project/alexandria/,,Alexandria}, a
  282. collection of portable public-domain utilities.
  283. @item
  284. @uref{http://www.cliki.net/trivial-features,,trivial-features}, a
  285. portability layer that ensures consistent @code{*features*} across
  286. multiple Common Lisp implementations.
  287. @end itemize
  288. Furthermore, if you wish to run the testsuite,
  289. @uref{http://www.cliki.net/rt,,RT} is required.
  290. You may find mechanisms such as
  291. @uref{https://www.quicklisp.org/beta/,Quicklisp} (recommended)
  292. or @uref{http://common-lisp.net/project/clbuild/,,clbuild} (for advanced
  293. uses) helpful in getting and managing @cffi{} and its
  294. dependencies.
  295. @c ===================================================================
  296. @c CHAPTER: Implementation Support
  297. @node Implementation Support, Tutorial, Installation, Top
  298. @chapter Implementation Support
  299. @cffi{} supports various free and commercial Lisp implementations:
  300. @acronym{ABCL}, Allegro CL, Clasp, @sc{clisp}, Clozure CL,
  301. @acronym{CMUCL}, Corman CL, @acronym{ECL}, @acronym{GCL}, LispWorks,
  302. @acronym{MCL}, @acronym{SBCL} and the Scieneer CL.
  303. In general, you should work with the latest versions of each
  304. implementation since those will usually be tested against recent
  305. versions of CFFI more often and might include necessary features or
  306. bug fixes. Reasonable patches for compatibility with earlier versions
  307. are welcome nevertheless.
  308. @section Limitations
  309. Some features are not supported in all implementations.
  310. @c TODO: describe these features here.
  311. @c flat-namespace too
  312. @subheading Allegro CL
  313. @itemize
  314. @item
  315. Does not support the @code{:long-long} type natively.
  316. @item
  317. Unicode support is limited to the Basic Multilingual Plane (16-bit
  318. code points).
  319. @end itemize
  320. @subheading Clasp
  321. @itemize
  322. @item
  323. Only supports a flat namespace.
  324. @end itemize
  325. @subheading CMUCL
  326. @itemize
  327. @item
  328. No Unicode support. (8-bit code points)
  329. @end itemize
  330. @subheading Corman CL
  331. @itemize
  332. @item
  333. Does not support @code{foreign-funcall}.
  334. @end itemize
  335. @subheading @acronym{ECL}
  336. @itemize
  337. @item
  338. On platforms where ECL's dynamic FFI is not supported (ie. when
  339. @code{:dffi} is not present in @code{*features*}),
  340. @code{cffi:load-foreign-library} does not work and you must use ECL's
  341. own @code{ffi:load-foreign-library} with a constant string argument.
  342. @end itemize
  343. @subheading Lispworks
  344. @itemize
  345. @item
  346. Does not completely support the @code{:long-long} type natively in
  347. 32-bit platforms.
  348. @item
  349. Unicode support is limited to the Basic Multilingual Plane (16-bit
  350. code points).
  351. @end itemize
  352. @subheading @acronym{SBCL}
  353. @itemize
  354. @item
  355. Not all platforms support callbacks.
  356. @end itemize
  357. @c ===================================================================
  358. @c CHAPTER: An Introduction to Foreign Interfaces and CFFI
  359. @c This macro is merely a marker that I don't think I'll use after
  360. @c all.
  361. @macro tutorialsource {text}
  362. @c \text\
  363. @end macro
  364. @c because I don't want to type this over and over
  365. @macro clikicffi
  366. http://www.cliki.net/CFFI
  367. @end macro
  368. @c TeX puts spurious newlines in when you use the above macro
  369. @c in @examples &c. So it is expanded below in some places.
  370. @node Tutorial, Wrapper generators, Implementation Support, Top
  371. @chapter An Introduction to Foreign Interfaces and @acronym{CFFI}
  372. @c Above, I don't use the cffi macro because it breaks TeX.
  373. @cindex tutorial, @cffi{}
  374. Users of many popular languages bearing semantic similarity to Lisp,
  375. such as Perl and Python, are accustomed to having access to popular C
  376. libraries, such as @acronym{GTK}, by way of ``bindings''. In Lisp, we
  377. do something similar, but take a fundamentally different approach.
  378. This tutorial first explains this difference, then explains how you
  379. can use @cffi{}, a powerful system for calling out to C and C++ and
  380. access C data from many Common Lisp implementations.
  381. @cindex foreign functions and data
  382. The concept can be generalized to other languages; at the time of
  383. writing, only @cffi{}'s C support is fairly complete. Therefore, we
  384. will interchangeably refer to @dfn{foreign functions} and @dfn{foreign
  385. data}, and ``C functions'' and ``C data''. At no time will the word
  386. ``foreign'' carry its usual, non-programming meaning.
  387. This tutorial expects you to have a working understanding of both
  388. Common Lisp and C, including the Common Lisp macro system.
  389. @menu
  390. * Tutorial-Comparison:: Why FFI?
  391. * Tutorial-Getting a URL:: An FFI use case.
  392. * Tutorial-Loading:: Load libcurl.so.
  393. * Tutorial-Initializing:: Call a function in libcurl.so.
  394. * Tutorial-easy_setopt:: An advanced libcurl function.
  395. * Tutorial-Abstraction:: Why breaking it is necessary.
  396. * Tutorial-Lisp easy_setopt:: Semi-Lispy option interface.
  397. * Tutorial-Memory:: In C, you collect the garbage.
  398. * Tutorial-Callbacks:: Make useful C function pointers.
  399. * Tutorial-Completion:: Minimal get-url functionality.
  400. * Tutorial-Types:: Defining new foreign types.
  401. * Tutorial-Conclusion:: What's next?
  402. @end menu
  403. @node Tutorial-Comparison, Tutorial-Getting a URL, Tutorial, Tutorial
  404. @section What makes Lisp different
  405. The following sums up how bindings to foreign libraries are usually
  406. implemented in other languages, then in Common Lisp:
  407. @table @asis
  408. @item Perl, Python, Java, other one-implementation languages
  409. @cindex @acronym{SWIG}
  410. @cindex Perl
  411. @cindex Python
  412. Bindings are implemented as shared objects written in C. In some
  413. cases, the C code is generated by a tool, such as @acronym{SWIG}, but
  414. the result is the same: a new C library that manually translates
  415. between the language implementation's objects, such as @code{PyObject}
  416. in Python, and whatever C object is called for, often using C
  417. functions provided by the implementation. It also translates between
  418. the calling conventions of the language and C.
  419. @item Common Lisp
  420. @cindex @acronym{SLIME}
  421. Bindings are written in Lisp. They can be created at-will by Lisp
  422. programs. Lisp programmers can write new bindings and add them to the
  423. image, using a listener such as @acronym{SLIME}, as easily as with
  424. regular Lisp definitions. The only foreign library to load is the one
  425. being wrapped---the one with the pure C interface; no C or other
  426. non-Lisp compilation is required.
  427. @end table
  428. @cindex advantages of @acronym{FFI}
  429. @cindex benefits of @acronym{FFI}
  430. We believe the advantages of the Common Lisp approach far outweigh any
  431. disadvantages. Incremental development with a listener can be as
  432. productive for C binding development as it is with other Lisp
  433. development. Keeping it ``in the [Lisp] family'', as it were, makes
  434. it much easier for you and other Lisp programmers to load and use the
  435. bindings. Common Lisp implementations such as @acronym{CMUCL}, freed
  436. from having to provide a C interface to their own objects, are thus
  437. freed to be implemented in another language (as @acronym{CMUCL} is)
  438. while still allowing programmers to call foreign functions.
  439. @cindex minimal bindings
  440. Perhaps the greatest advantage is that using an @acronym{FFI} doesn't
  441. obligate you to become a professional binding developer. Writers of
  442. bindings for other languages usually end up maintaining or failing to
  443. maintain complete bindings to the foreign library. Using an
  444. @acronym{FFI}, however, means if you only need one or two functions,
  445. you can write bindings for only those functions, and be assured that
  446. you can just as easily add to the bindings if need be.
  447. @cindex C abstractions
  448. @cindex abstractions in C
  449. The removal of the C compiler, or C interpretation of any kind,
  450. creates the main disadvantage: some of C's ``abstractions'' are not
  451. available, violating information encapsulation. For example,
  452. @code{struct}s that must be passed on the stack, or used as return
  453. values, without corresponding functional abstractions to create and
  454. manage the @code{struct}s, must be declared explicitly in Lisp. This
  455. is fine for structs whose contents are ``public'', but is not so
  456. pleasant when a struct is supposed to be ``opaque'' by convention,
  457. even though it is not so defined.@footnote{Admittedly, this is an
  458. advanced issue, and we encourage you to leave this text until you are
  459. more familiar with how @cffi{} works.}
  460. Without an abstraction to create the struct, Lisp needs to be able to
  461. lay out the struct in memory, so must know its internal details.
  462. @cindex workaround for C
  463. In these cases, you can create a minimal C library to provide the
  464. missing abstractions, without destroying all the advantages of the
  465. Common Lisp approach discussed above. In the case of @code{struct}s,
  466. you can write simple, pure C functions that tell you how many bytes a
  467. struct requires or allocate new structs, read and write fields of the
  468. struct, or whatever operations are supposed to be
  469. public.@footnote{This does not apply to structs whose contents are
  470. intended to be part of the public library interface. In those cases,
  471. a pure Lisp struct definition is always preferred. In fact, many
  472. prefer to stay in Lisp and break the encapsulation anyway, placing the
  473. burden of correct library interface definition on the library.}
  474. @ref{The Groveller} automates this and other processes.
  475. Another disadvantage appears when you would rather use the foreign
  476. language than Lisp. However, someone who prefers C to Lisp is not a
  477. likely candidate for developing a Lisp interface to a C library.
  478. @node Tutorial-Getting a URL, Tutorial-Loading, Tutorial-Comparison, Tutorial
  479. @section Getting a @acronym{URL}
  480. @cindex c@acronym{URL}
  481. The widely available @code{libcurl} is a library for downloading files
  482. over protocols like @acronym{HTTP}. We will use @code{libcurl} with
  483. @cffi{} to download a web page.
  484. Please note that there are many other ways to download files from the
  485. web, not least the @sc{cl-curl} project to provide bindings to
  486. @code{libcurl} via a similar @acronym{FFI}.@footnote{Specifically,
  487. @acronym{UFFI}, an older @acronym{FFI} that takes a somewhat different
  488. approach compared to @cffi{}. I believe that these days (December
  489. 2005) @cffi{} is more portable and actively developed, though not as
  490. mature yet. Consensus in the free @sc{unix} Common Lisp community
  491. seems to be that @cffi{} is preferred for new development, though
  492. @acronym{UFFI} will likely go on for quite some time as many projects
  493. already use it. @cffi{} includes the @code{UFFI-COMPAT} package for
  494. complete compatibility with @acronym{UFFI}.}
  495. @uref{http://curl.haxx.se/libcurl/c/libcurl-tutorial.html,,libcurl-tutorial(3)}
  496. is a tutorial for @code{libcurl} programming in C. We will follow
  497. that to develop a binding to download a file. We will also use
  498. @file{curl.h}, @file{easy.h}, and the @command{man} pages for the
  499. @code{libcurl} function, all available in the @samp{curl-dev} package
  500. or equivalent for your system, or in the c@acronym{URL} source code
  501. package. If you have the development package, the headers should be
  502. installed in @file{/usr/include/curl/}, and the @command{man} pages
  503. may be accessed through your favorite @command{man} facility.
  504. @node Tutorial-Loading, Tutorial-Initializing, Tutorial-Getting a URL, Tutorial
  505. @section Loading foreign libraries
  506. @cindex loading @cffi{}
  507. @cindex requiring @cffi{}
  508. First of all, we will create a package to work in. You can save these
  509. forms in a file, or just send them to the listener as they are. If
  510. creating bindings for an @acronym{ASDF} package of yours, you will
  511. want to add @code{:cffi} to the @code{:depends-on} list in your
  512. @file{.asd} file. Otherwise, just use the @code{asdf:load-system} function to
  513. load @cffi{}.
  514. @tutorialsource{Initialization}
  515. @lisp
  516. (asdf:load-system :cffi)
  517. ;;; @lispcmt{Nothing special about the "CFFI-USER" package. We're just}
  518. ;;; @lispcmt{using it as a substitute for your own CL package.}
  519. (defpackage :cffi-user
  520. (:use :common-lisp :cffi))
  521. (in-package :cffi-user)
  522. (define-foreign-library libcurl
  523. (:darwin (:or "libcurl.3.dylib" "libcurl.dylib"))
  524. (:unix (:or "libcurl.so.3" "libcurl.so"))
  525. (t (:default "libcurl")))
  526. (use-foreign-library libcurl)
  527. @end lisp
  528. @cindex foreign library load
  529. @cindex library, foreign
  530. Using @code{define-foreign-library} and @code{use-foreign-library}, we
  531. have loaded @code{libcurl} into Lisp, much as the linker does when you
  532. start a C program, or @code{common-lisp:load} does with a Lisp source
  533. file or @acronym{FASL} file. We special-cased for @sc{unix} machines
  534. to always load a particular version, the one this tutorial was tested
  535. with; for those who don't care, the @code{define-foreign-library}
  536. clause @code{(t (:default "libcurl"))} should be satisfactory, and
  537. will adapt to various operating systems.
  538. @node Tutorial-Initializing, Tutorial-easy_setopt, Tutorial-Loading, Tutorial
  539. @section Initializing @code{libcurl}
  540. @cindex function definition
  541. After the introductory matter, the tutorial goes on to present the
  542. first function you should use.
  543. @example
  544. CURLcode curl_global_init(long flags);
  545. @end example
  546. @noindent
  547. Let's pick this apart into appropriate Lisp code:
  548. @tutorialsource{First CURLcode}
  549. @lisp
  550. ;;; @lispcmt{A CURLcode is the universal error code. curl/curl.h says}
  551. ;;; @lispcmt{no return code will ever be removed, and new ones will be}
  552. ;;; @lispcmt{added to the end.}
  553. (defctype curl-code :int)
  554. ;;; @lispcmt{Initialize libcurl with FLAGS.}
  555. (defcfun "curl_global_init" curl-code
  556. (flags :long))
  557. @end lisp
  558. @impnote{By default, CFFI assumes the UNIX viewpoint that there is one
  559. C symbol namespace, containing all symbols in all loaded objects.
  560. This is not so on Windows and Darwin, but we emulate UNIX's behaviour
  561. there. @ref{defcfun} for more details.}
  562. Note the parallels with the original C declaration. We've defined
  563. @code{curl-code} as a wrapping type for @code{:int}; right now, it
  564. only marks it as special, but later we will do something more
  565. interesting with it. The point is that we don't have to do it yet.
  566. @cindex calling foreign functions
  567. Looking at @file{curl.h}, @code{CURL_GLOBAL_NOTHING}, a possible value
  568. for @code{flags} above, is defined as @samp{0}. So we can now call
  569. the function:
  570. @example
  571. @sc{cffi-user>} (curl-global-init 0)
  572. @result{} 0
  573. @end example
  574. @cindex looks like it worked
  575. Looking at @file{curl.h} again, @code{0} means @code{CURLE_OK}, so it
  576. looks like the call succeeded. Note that @cffi{} converted the
  577. function name to a Lisp-friendly name. You can specify your own name
  578. if you want; use @code{("curl_global_init" @var{your-name-here})} as
  579. the @var{name} argument to @code{defcfun}.
  580. The tutorial goes on to have us allocate a handle. For good measure,
  581. we should also include the deallocator. Let's look at these
  582. functions:
  583. @example
  584. CURL *curl_easy_init( );
  585. void curl_easy_cleanup(CURL *handle);
  586. @end example
  587. Advanced users may want to define special pointer types; we will
  588. explore this possibility later. For now, just treat every pointer as
  589. the same:
  590. @tutorialsource{curl_easy handles}
  591. @lisp
  592. (defcfun "curl_easy_init" :pointer)
  593. (defcfun "curl_easy_cleanup" :void
  594. (easy-handle :pointer))
  595. @end lisp
  596. Now we can continue with the tutorial:
  597. @example
  598. @sc{cffi-user>} (defparameter *easy-handle* (curl-easy-init))
  599. @result{} *EASY-HANDLE*
  600. @sc{cffi-user>} *easy-handle*
  601. @result{} #<FOREIGN-ADDRESS #x09844EE0>
  602. @end example
  603. @cindex pointers in Lisp
  604. Note the print representation of a pointer. It changes depending on
  605. what Lisp you are using, but that doesn't make any difference to
  606. @cffi{}.
  607. @node Tutorial-easy_setopt, Tutorial-Abstraction, Tutorial-Initializing, Tutorial
  608. @section Setting download options
  609. The @code{libcurl} tutorial says we'll want to set many options before
  610. performing any download actions. This is done through
  611. @code{curl_easy_setopt}:
  612. @c That is literally ..., not an ellipsis.
  613. @example
  614. CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...);
  615. @end example
  616. @cindex varargs
  617. @cindex foreign arguments
  618. We've introduced a new twist: variable arguments. There is no obvious
  619. translation to the @code{defcfun} form, particularly as there are four
  620. possible argument types. Because of the way C works, we could define
  621. four wrappers around @code{curl_easy_setopt}, one for each type; in
  622. this case, however, we'll use the general-purpose macro
  623. @code{foreign-funcall} to call this function.
  624. @cindex enumeration, C
  625. To make things easier on ourselves, we'll create an enumeration of the
  626. kinds of options we want to set. The @code{enum CURLoption} isn't the
  627. most straightforward, but reading the @code{CINIT} C macro definition
  628. should be enlightening.
  629. @tutorialsource{CURLoption enumeration}
  630. @lisp
  631. (defmacro define-curl-options (name type-offsets &rest enum-args)
  632. "As with CFFI:DEFCENUM, except each of ENUM-ARGS is as follows:
  633. (NAME TYPE NUMBER)
  634. Where the arguments are as they are with the CINIT macro defined
  635. in curl.h, except NAME is a keyword.
  636. TYPE-OFFSETS is a plist of TYPEs to their integer offsets, as
  637. defined by the CURLOPTTYPE_LONG et al constants in curl.h."
  638. (flet ((enumerated-value (type offset)
  639. (+ (getf type-offsets type) offset)))
  640. `(progn
  641. (defcenum ,name
  642. ,@@(loop for (name type number) in enum-args
  643. collect (list name (enumerated-value type number))))
  644. ',name))) ;@lispcmt{for REPL users' sanity}
  645. (define-curl-options curl-option
  646. (long 0 objectpoint 10000 functionpoint 20000 off-t 30000)
  647. (:noprogress long 43)
  648. (:nosignal long 99)
  649. (:errorbuffer objectpoint 10)
  650. (:url objectpoint 2))
  651. @end lisp
  652. With some well-placed Emacs @code{query-replace-regexp}s, you could
  653. probably similarly define the entire @code{CURLoption} enumeration. I
  654. have selected to transcribe a few that we will use in this tutorial.
  655. If you're having trouble following the macrology, just macroexpand the
  656. @code{curl-option} definition, or see the following macroexpansion,
  657. conveniently downcased and reformatted:
  658. @tutorialsource{DEFINE-CURL-OPTIONS macroexpansion}
  659. @lisp
  660. (progn
  661. (defcenum curl-option
  662. (:noprogress 43)
  663. (:nosignal 99)
  664. (:errorbuffer 10010)
  665. (:url 10002))
  666. 'curl-option)
  667. @end lisp
  668. @noindent
  669. That seems more than reasonable. You may notice that we only use the
  670. @var{type} to compute the real enumeration offset; we will also need
  671. the type information later.
  672. First, however, let's make sure a simple call to the foreign function
  673. works:
  674. @example
  675. @sc{cffi-user>} (foreign-funcall "curl_easy_setopt"
  676. :pointer *easy-handle*
  677. curl-option :nosignal :long 1 curl-code)
  678. @result{} 0
  679. @end example
  680. @code{foreign-funcall}, despite its surface simplicity, can be used to
  681. call any C function. Its first argument is a string, naming the
  682. function to be called. Next, for each argument, we pass the name of
  683. the C type, which is the same as in @code{defcfun}, followed by a Lisp
  684. object representing the data to be passed as the argument. The final
  685. argument is the return type, for which we use the @code{curl-code}
  686. type defined earlier.
  687. @code{defcfun} just puts a convenient fa@,cade on
  688. @code{foreign-funcall}.@footnote{This isn't entirely true; some Lisps
  689. don't support @code{foreign-funcall}, so @code{defcfun} is implemented
  690. without it. @code{defcfun} may also perform optimizations that
  691. @code{foreign-funcall} cannot.} Our earlier call to
  692. @code{curl-global-init} could have been written as follows:
  693. @example
  694. @sc{cffi-user>} (foreign-funcall "curl_global_init" :long 0
  695. curl-code)
  696. @result{} 0
  697. @end example
  698. Before we continue, we will take a look at what @cffi{} can and can't
  699. do, and why this is so.
  700. @node Tutorial-Abstraction, Tutorial-Lisp easy_setopt, Tutorial-easy_setopt, Tutorial
  701. @section Breaking the abstraction
  702. @cindex breaking the abstraction
  703. @cindex abstraction breaking
  704. In @ref{Tutorial-Comparison,, What makes Lisp different}, we mentioned
  705. that writing an @acronym{FFI} sometimes requires depending on
  706. information not provided as part of the interface. The easy option
  707. @code{CURLOPT_WRITEDATA}, which we will not provide as part of the
  708. Lisp interface, illustrates this issue.
  709. Strictly speaking, the @code{curl-option} enumeration is not
  710. necessary; we could have used @code{:int 99} instead of
  711. @code{curl-option :nosignal} in our call to @code{curl_easy_setopt}
  712. above. We defined it anyway, in part to hide the fact that we are
  713. breaking the abstraction that the C @code{enum} provides. If the
  714. c@acronym{URL} developers decide to change those numbers later, we
  715. must change the Lisp enumeration, because enumeration values are not
  716. provided in the compiled C library, @code{libcurl.so.3}.
  717. @cffi{} works because the most useful things in C libraries ---
  718. non-static functions and non-static variables --- are included
  719. accessibly in @code{libcurl.so.3}. A C compiler that violated this
  720. would be considered a worthless compiler.
  721. The other thing @code{define-curl-options} does is give the ``type''
  722. of the third argument passed to @code{curl_easy_setopt}. Using this
  723. information, we can tell that the @code{:nosignal} option should
  724. accept a long integer argument. We can implicitly assume @code{t}
  725. @equiv{} 1 and @code{nil} @equiv{} 0, as it is in C, which takes care
  726. of the fact that @code{CURLOPT_NOSIGNAL} is really asking for a
  727. boolean.
  728. The ``type'' of @code{CURLOPT_WRITEDATA} is @code{objectpoint}.
  729. However, it is really looking for a @code{FILE*}.
  730. @code{CURLOPT_ERRORBUFFER} is looking for a @code{char*}, so there is
  731. no obvious @cffi{} type but @code{:pointer}.
  732. The first thing to note is that nowhere in the C interface includes
  733. this information; it can only be found in the manual. We could
  734. disjoin these clearly different types ourselves, by splitting
  735. @code{objectpoint} into @code{filepoint} and @code{charpoint}, but we
  736. are still breaking the abstraction, because we have to augment the
  737. entire enumeration form with this additional
  738. information.@footnote{Another possibility is to allow the caller to
  739. specify the desired C type of the third argument. This is essentially
  740. what happens in a call to the function written in C.}
  741. @cindex streams and C
  742. @cindex @sc{file}* and streams
  743. The second is that the @code{CURLOPT_WRITEDATA} argument is completely
  744. incompatible with the desired Lisp data, a
  745. stream.@footnote{@xref{Other Kinds of Streams,,, libc, GNU C Library
  746. Reference}, for a @acronym{GNU}-only way to extend the @code{FILE*}
  747. type. You could use this to convert Lisp streams to the needed C
  748. data. This would be quite involved and far outside the scope of this
  749. tutorial.} It is probably acceptable if we are controlling every file
  750. we might want to use as this argument, in which case we can just call
  751. the foreign function @code{fopen}. Regardless, though, we can't write
  752. to arbitrary streams, which is exactly what we want to do for this
  753. application.
  754. Finally, note that the @code{curl_easy_setopt} interface itself is a
  755. hack, intended to work around some of the drawbacks of C. The
  756. definition of @code{Curl_setopt}, while long, is far less cluttered
  757. than the equivalent disjoint-function set would be; in addition,
  758. setting a new option in an old @code{libcurl} can generate a run-time
  759. error rather than breaking the compile. Lisp can just as concisely
  760. generate functions as compare values, and the ``undefined function''
  761. error is just as useful as any explicit error we could define here
  762. might be.
  763. @node Tutorial-Lisp easy_setopt, Tutorial-Memory, Tutorial-Abstraction, Tutorial
  764. @section Option functions in Lisp
  765. We could use @code{foreign-funcall} directly every time we wanted to
  766. call @code{curl_easy_setopt}. However, we can encapsulate some of the
  767. necessary information with the following.
  768. @lisp
  769. ;;; @lispcmt{We will use this type later in a more creative way. For}
  770. ;;; @lispcmt{now, just consider it a marker that this isn't just any}
  771. ;;; @lispcmt{pointer.}
  772. (defctype easy-handle :pointer)
  773. (defmacro curl-easy-setopt (easy-handle enumerated-name
  774. value-type new-value)
  775. "Call `curl_easy_setopt' on EASY-HANDLE, using ENUMERATED-NAME
  776. as the OPTION. VALUE-TYPE is the CFFI foreign type of the third
  777. argument, and NEW-VALUE is the Lisp data to be translated to the
  778. third argument. VALUE-TYPE is not evaluated."
  779. `(foreign-funcall "curl_easy_setopt" easy-handle ,easy-handle
  780. curl-option ,enumerated-name
  781. ,value-type ,new-value curl-code))
  782. @end lisp
  783. Now we define a function for each kind of argument that encodes the
  784. correct @code{value-type} in the above. This can be done reasonably
  785. in the @code{define-curl-options} macroexpansion; after all, that is
  786. where the different options are listed!
  787. @cindex Lispy C functions
  788. We could make @code{cl:defun} forms in the expansion that simply call
  789. @code{curl-easy-setopt}; however, it is probably easier and clearer to
  790. use @code{defcfun}. @code{define-curl-options} was becoming unwieldy,
  791. so I defined some helpers in this new definition.
  792. @smalllisp
  793. (defun curry-curl-option-setter (function-name option-keyword)
  794. "Wrap the function named by FUNCTION-NAME with a version that
  795. curries the second argument as OPTION-KEYWORD.
  796. This function is intended for use in DEFINE-CURL-OPTION-SETTER."
  797. (setf (symbol-function function-name)
  798. (let ((c-function (symbol-function function-name)))
  799. (lambda (easy-handle new-value)
  800. (funcall c-function easy-handle option-keyword
  801. new-value)))))
  802. (defmacro define-curl-option-setter (name option-type
  803. option-value foreign-type)
  804. "Define (with DEFCFUN) a function NAME that calls
  805. curl_easy_setopt. OPTION-TYPE and OPTION-VALUE are the CFFI
  806. foreign type and value to be passed as the second argument to
  807. easy_setopt, and FOREIGN-TYPE is the CFFI foreign type to be used
  808. for the resultant function's third argument.
  809. This macro is intended for use in DEFINE-CURL-OPTIONS."
  810. `(progn
  811. (defcfun ("curl_easy_setopt" ,name) curl-code
  812. (easy-handle easy-handle)
  813. (option ,option-type)
  814. (new-value ,foreign-type))
  815. (curry-curl-option-setter ',name ',option-value)))
  816. (defmacro define-curl-options (type-name type-offsets &rest enum-args)
  817. "As with CFFI:DEFCENUM, except each of ENUM-ARGS is as follows:
  818. (NAME TYPE NUMBER)
  819. Where the arguments are as they are with the CINIT macro defined
  820. in curl.h, except NAME is a keyword.
  821. TYPE-OFFSETS is a plist of TYPEs to their integer offsets, as
  822. defined by the CURLOPTTYPE_LONG et al constants in curl.h.
  823. Also, define functions for each option named
  824. set-`TYPE-NAME'-`OPTION-NAME', where OPTION-NAME is the NAME from
  825. the above destructuring."
  826. (flet ((enumerated-value (type offset)
  827. (+ (getf type-offsets type) offset))
  828. ;; @lispcmt{map PROCEDURE, destructuring each of ENUM-ARGS}
  829. (map-enum-args (procedure)
  830. (mapcar (lambda (arg) (apply procedure arg)) enum-args))
  831. ;; @lispcmt{build a name like SET-CURL-OPTION-NOSIGNAL}
  832. (make-setter-name (option-name)
  833. (intern (concatenate
  834. 'string "SET-" (symbol-name type-name)
  835. "-" (symbol-name option-name)))))
  836. `(progn
  837. (defcenum ,type-name
  838. ,@@(map-enum-args
  839. (lambda (name type number)
  840. (list name (enumerated-value type number)))))
  841. ,@@(map-enum-args
  842. (lambda (name type number)
  843. (declare (ignore number))
  844. `(define-curl-option-setter ,(make-setter-name name)
  845. ,type-name ,name ,(ecase type
  846. (long :long)
  847. (objectpoint :pointer)
  848. (functionpoint :pointer)
  849. (off-t :long)))))
  850. ',type-name)))
  851. @end smalllisp
  852. @noindent
  853. Macroexpanding our @code{define-curl-options} form once more, we
  854. see something different:
  855. @lisp
  856. (progn
  857. (defcenum curl-option
  858. (:noprogress 43)
  859. (:nosignal 99)
  860. (:errorbuffer 10010)
  861. (:url 10002))
  862. (define-curl-option-setter set-curl-option-noprogress
  863. curl-option :noprogress :long)
  864. (define-curl-option-setter set-curl-option-nosignal
  865. curl-option :nosignal :long)
  866. (define-curl-option-setter set-curl-option-errorbuffer
  867. curl-option :errorbuffer :pointer)
  868. (define-curl-option-setter set-curl-option-url
  869. curl-option :url :pointer)
  870. 'curl-option)
  871. @end lisp
  872. @noindent
  873. Macroexpanding one of the new @code{define-curl-option-setter}
  874. forms yields the following:
  875. @lisp
  876. (progn
  877. (defcfun ("curl_easy_setopt" set-curl-option-nosignal) curl-code
  878. (easy-handle easy-handle)
  879. (option curl-option)
  880. (new-value :long))
  881. (curry-curl-option-setter 'set-curl-option-nosignal ':nosignal))
  882. @end lisp
  883. @noindent
  884. Finally, let's try this out:
  885. @example
  886. @sc{cffi-user>} (set-curl-option-nosignal *easy-handle* 1)
  887. @result{} 0
  888. @end example
  889. @noindent
  890. Looks like it works just as well. This interface is now reasonably
  891. high-level to wash out some of the ugliness of the thinnest possible
  892. @code{curl_easy_setopt} @acronym{FFI}, without obscuring the remaining
  893. C bookkeeping details we will explore.
  894. @node Tutorial-Memory, Tutorial-Callbacks, Tutorial-Lisp easy_setopt, Tutorial
  895. @section Memory management
  896. According to the documentation for @code{curl_easy_setopt}, the type
  897. of the third argument when @var{option} is @code{CURLOPT_ERRORBUFFER}
  898. is @code{char*}. Above, we've defined
  899. @code{set-curl-option-errorbuffer} to accept a @code{:pointer} as the
  900. new option value. However, there is a @cffi{} type @code{:string},
  901. which translates Lisp strings to C strings when passed as arguments to
  902. foreign function calls. Why not, then, use @code{:string} as the
  903. @cffi{} type of the third argument? There are two reasons, both
  904. related to the necessity of breaking abstraction described in
  905. @ref{Tutorial-Abstraction,, Breaking the abstraction}.
  906. The first reason also applies to @code{CURLOPT_URL}, which we will use
  907. to illustrate the point. Assuming we have changed the type of the
  908. third argument underlying @code{set-curl-option-url} to
  909. @code{:string}, look at these two equivalent forms.
  910. @lisp
  911. (set-curl-option-url *easy-handle* "http://www.cliki.net/CFFI")
  912. @equiv{} (with-foreign-string (url "http://www.cliki.net/CFFI")
  913. (foreign-funcall "curl_easy_setopt" easy-handle *easy-handle*
  914. curl-option :url :pointer url curl-code))
  915. @end lisp
  916. @noindent
  917. The latter, in fact, is mostly equivalent to what a foreign function
  918. call's macroexpansion actually does. As you can see, the Lisp string
  919. @code{"@clikicffi{}"} is copied into a @code{char} array and
  920. null-terminated; the pointer to beginning of this array, now a C
  921. string, is passed as a @cffi{} @code{:pointer} to the foreign
  922. function.
  923. @cindex dynamic extent
  924. @cindex foreign values with dynamic extent
  925. Unfortunately, the C abstraction has failed us, and we must break it.
  926. While @code{:string} works well for many @code{char*} arguments, it
  927. does not for cases like this. As the @code{curl_easy_setopt}
  928. documentation explains, ``The string must remain present until curl no
  929. longer needs it, as it doesn't copy the string.'' The C string
  930. created by @code{with-foreign-string}, however, only has dynamic
  931. extent: it is ``deallocated'' when the body (above containing the
  932. @code{foreign-funcall} form) exits.
  933. @cindex premature deallocation
  934. If we are supposed to keep the C string around, but it goes away, what
  935. happens when some @code{libcurl} function tries to access the
  936. @acronym{URL} string? We have reentered the dreaded world of C
  937. ``undefined behavior''. In some Lisps, it will probably get a chunk
  938. of the Lisp/C stack. You may segfault. You may get some random piece
  939. of other data from the heap. Maybe, in a world where ``dynamic
  940. extent'' is defined to be ``infinite extent'', everything will turn
  941. out fine. Regardless, results are likely to be almost universally
  942. unpleasant.@footnote{``@i{But I thought Lisp was supposed to protect
  943. me from all that buggy C crap!}'' Before asking a question like that,
  944. remember that you are a stranger in a foreign land, whose residents
  945. have a completely different set of values.}
  946. Returning to the current @code{set-curl-option-url} interface, here is
  947. what we must do:
  948. @lisp
  949. (let (easy-handle)
  950. (unwind-protect
  951. (with-foreign-string (url "http://www.cliki.net/CFFI")
  952. (setf easy-handle (curl-easy-init))
  953. (set-curl-option-url easy-handle url)
  954. #|@lispcmt{do more with the easy-handle, like actually get the URL}|#)
  955. (when easy-handle
  956. (curl-easy-cleanup easy-handle))))
  957. @end lisp
  958. @c old comment to luis: I go on to say that this isn't obviously
  959. @c extensible to new option settings that require C strings to stick
  960. @c around, as it would involve re-evaluating the unwind-protect form
  961. @c with more dynamic memory allocation. So I plan to show how to
  962. @c write something similar to ObjC's NSAutoreleasePool, to be managed
  963. @c with a simple unwind-protect form.
  964. @noindent
  965. That is fine for the single string defined here, but for every string
  966. option we want to pass, we have to surround the body of
  967. @code{with-foreign-string} with another @code{with-foreign-string}
  968. wrapper, or else do some extremely error-prone pointer manipulation
  969. and size calculation in advance. We could alleviate some of the pain
  970. with a recursively expanding macro, but this would not remove the need
  971. to modify the block every time we want to add an option, anathema as
  972. it is to a modular interface.
  973. Before modifying the code to account for this case, consider the other
  974. reason we can't simply use @code{:string} as the foreign type. In C,
  975. a @code{char *} is a @code{char *}, not necessarily a string. The
  976. option @code{CURLOPT_ERRORBUFFER} accepts a @code{char *}, but does
  977. not expect anything about the data there. However, it does expect
  978. that some @code{libcurl} function we call later can write a C string
  979. of up to 255 characters there. We, the callers of the function, are
  980. expected to read the C string at a later time, exactly the opposite of
  981. what @code{:string} implies.
  982. With the semantics for an input string in mind --- namely, that the
  983. string should be kept around until we @code{curl_easy_cleanup} the
  984. easy handle --- we are ready to extend the Lisp interface:
  985. @lisp
  986. (defvar *easy-handle-cstrings* (make-hash-table)
  987. "Hashtable of easy handles to lists of C strings that may be
  988. safely freed after the handle is freed.")
  989. (defun make-easy-handle ()
  990. "Answer a new CURL easy interface handle, to which the lifetime
  991. of C strings may be tied. See `add-curl-handle-cstring'."
  992. (let ((easy-handle (curl-easy-init)))
  993. (setf (gethash easy-handle *easy-handle-cstrings*) '())
  994. easy-handle))
  995. (defun free-easy-handle (handle)
  996. "Free CURL easy interface HANDLE and any C strings created to
  997. be its options."
  998. (curl-easy-cleanup handle)
  999. (mapc #'foreign-string-free
  1000. (gethash handle *easy-handle-cstrings*))
  1001. (remhash handle *easy-handle-cstrings*))
  1002. (defun add-curl-handle-cstring (handle cstring)
  1003. "Add CSTRING to be freed when HANDLE is, answering CSTRING."
  1004. (car (push cstring (gethash handle *easy-handle-cstrings*))))
  1005. @end lisp
  1006. @noindent
  1007. Here we have redefined the interface to create and free handles, to
  1008. associate a list of allocated C strings with each handle while it
  1009. exists. The strategy of using different function names to wrap around
  1010. simple foreign functions is more common than the solution implemented
  1011. earlier with @code{curry-curl-option-setter}, which was to modify the
  1012. function name's function slot.@footnote{There are advantages and
  1013. disadvantages to each approach; I chose to @code{(setf
  1014. symbol-function)} earlier because it entailed generating fewer magic
  1015. function names.}
  1016. Incidentally, the next step is to redefine
  1017. @code{curry-curl-option-setter} to allocate C strings for the
  1018. appropriate length of time, given a Lisp string as the
  1019. @code{new-value} argument:
  1020. @lisp
  1021. (defun curry-curl-option-setter (function-name option-keyword)
  1022. "Wrap the function named by FUNCTION-NAME with a version that
  1023. curries the second argument as OPTION-KEYWORD.
  1024. This function is intended for use in DEFINE-CURL-OPTION-SETTER."
  1025. (setf (symbol-function function-name)
  1026. (let ((c-function (symbol-function function-name)))
  1027. (lambda (easy-handle new-value)
  1028. (funcall c-function easy-handle option-keyword
  1029. (if (stringp new-value)
  1030. (add-curl-handle-cstring
  1031. easy-handle
  1032. (foreign-string-alloc new-value))
  1033. new-value))))))
  1034. @end lisp
  1035. @noindent
  1036. A quick analysis of the code shows that you need only reevaluate the
  1037. @code{curl-option} enumeration definition to take advantage of these
  1038. new semantics. Now, for good measure, let's reallocate the handle
  1039. with the new functions we just defined, and set its @acronym{URL}:
  1040. @example
  1041. @sc{cffi-user>} (curl-easy-cleanup *easy-handle*)
  1042. @result{} NIL
  1043. @sc{cffi-user>} (setf *easy-handle* (make-easy-handle))
  1044. @result{} #<FOREIGN-ADDRESS #x09844EE0>
  1045. @sc{cffi-user>} (set-curl-option-nosignal *easy-handle* 1)
  1046. @result{} 0
  1047. @sc{cffi-user>} (set-curl-option-url *easy-handle*
  1048. "http://www.cliki.net/CFFI")
  1049. @result{} 0
  1050. @end example
  1051. @cindex strings
  1052. For fun, let's inspect the Lisp value of the C string that was created
  1053. to hold @code{"@clikicffi{}"}. By virtue of the implementation of
  1054. @code{add-curl-handle-cstring}, it should be accessible through the
  1055. hash table defined:
  1056. @example
  1057. @sc{cffi-user>} (foreign-string-to-lisp
  1058. (car (gethash *easy-handle* *easy-handle-cstrings*)))
  1059. @result{} "http://www.cliki.net/CFFI"
  1060. @end example
  1061. @noindent
  1062. Looks like that worked, and @code{libcurl} now knows what
  1063. @acronym{URL} we want to retrieve.
  1064. Finally, we turn back to the @code{:errorbuffer} option mentioned at
  1065. the beginning of this section. Whereas the abstraction added to
  1066. support string inputs works fine for cases like @code{CURLOPT_URL}, it
  1067. hides the detail of keeping the C string; for @code{:errorbuffer},
  1068. however, we need that C string.
  1069. In a moment, we'll define something slightly cleaner, but for now,
  1070. remember that you can always hack around anything. We're modifying
  1071. handle creation, so make sure you free the old handle before
  1072. redefining @code{free-easy-handle}.
  1073. @smalllisp
  1074. (defvar *easy-handle-errorbuffers* (make-hash-table)
  1075. "Hashtable of easy handles to C strings serving as error
  1076. writeback buffers.")
  1077. ;;; @lispcmt{An extra byte is very little to pay for peace of mind.}
  1078. (defparameter *curl-error-size* 257
  1079. "Minimum char[] size used by cURL to report errors.")
  1080. (defun make-easy-handle ()
  1081. "Answer a new CURL easy interface handle, to which the lifetime
  1082. of C strings may be tied. See `add-curl-handle-cstring'."
  1083. (let ((easy-handle (curl-easy-init)))
  1084. (setf (gethash easy-handle *easy-handle-cstrings*) '())
  1085. (setf (gethash easy-handle *easy-handle-errorbuffers*)
  1086. (foreign-alloc :char :count *curl-error-size*
  1087. :initial-element 0))
  1088. easy-handle))
  1089. (defun free-easy-handle (handle)
  1090. "Free CURL easy interface HANDLE and any C strings created to
  1091. be its options."
  1092. (curl-easy-cleanup handle)
  1093. (foreign-free (gethash handle *easy-handle-errorbuffers*))
  1094. (remhash handle *easy-handle-errorbuffers*)
  1095. (mapc #'foreign-string-free
  1096. (gethash handle *easy-handle-cstrings*))
  1097. (remhash handle *easy-handle-cstrings*))
  1098. (defun get-easy-handle-error (handle)
  1099. "Answer a string containing HANDLE's current error message."
  1100. (foreign-string-to-lisp
  1101. (gethash handle *easy-handle-errorbuffers*)))
  1102. @end smalllisp
  1103. Be sure to once again set the options we've set thus far. You may
  1104. wish to define yet another wrapper function to do this.
  1105. @node Tutorial-Callbacks, Tutorial-Completion, Tutorial-Memory, Tutorial
  1106. @section Calling Lisp from C
  1107. If you have been reading
  1108. @uref{http://curl.haxx.se/libcurl/c/curl_easy_setopt.html,,
  1109. @code{curl_easy_setopt(3)}}, you should have noticed that some options
  1110. accept a function pointer. In particular, we need one function
  1111. pointer to set as @code{CURLOPT_WRITEFUNCTION}, to be called by
  1112. @code{libcurl} rather than the reverse, in order to receive data as it
  1113. is downloaded.
  1114. A binding writer without the aid of @acronym{FFI} usually approaches
  1115. this problem by writing a C function that accepts C data, converts to
  1116. the language's internal objects, and calls the callback provided by
  1117. the user, again in a reverse of usual practices.
  1118. The @cffi{} approach to callbacks precisely mirrors its differences
  1119. with the non-@acronym{FFI} approach on the ``calling C from Lisp''
  1120. side, which we have dealt with exclusively up to now. That is, you
  1121. define a callback function in Lisp using @code{defcallback}, and
  1122. @cffi{} effectively creates a C function to be passed as a function
  1123. pointer.
  1124. @impnote{This is much trickier than calling C functions from Lisp, as
  1125. it literally involves somehow generating a new C function that is as
  1126. good as any created by the compiler. Therefore, not all Lisps support
  1127. them. @xref{Implementation Support}, for information about @cffi{}
  1128. support issues in this and other areas. You may want to consider
  1129. changing to a Lisp that supports callbacks in order to continue with
  1130. this tutorial.}
  1131. @cindex callback definition
  1132. @cindex defining callbacks
  1133. Defining a callback is very similar to defining a callout; the main
  1134. difference is that we must provide some Lisp forms to be evaluated as
  1135. part of the callback. Here is the signature for the function the
  1136. @code{:writefunction} option takes:
  1137. @example
  1138. size_t
  1139. @var{function}(void *ptr, size_t size, size_t nmemb, void *stream);
  1140. @end example
  1141. @impnote{size_t is almost always an unsigned int. You can get this
  1142. and many other types using feature tests for your system by using
  1143. cffi-grovel.}
  1144. The above signature trivially translates into a @cffi{}
  1145. @code{defcallback} form, as follows.
  1146. @lisp
  1147. ;;; @lispcmt{Alias in case size_t changes.}
  1148. (defctype size :unsigned-int)
  1149. ;;; @lispcmt{To be set as the CURLOPT_WRITEFUNCTION of every easy handle.}
  1150. (defcallback easy-write size ((ptr :pointer) (size size)
  1151. (nmemb size) (stream :pointer))
  1152. (let ((data-size (* size nmemb)))
  1153. (handler-case
  1154. ;; @lispcmt{We use the dynamically-bound *easy-write-procedure* to}
  1155. ;; @lispcmt{call a closure with useful lexical context.}
  1156. (progn (funcall (symbol-value '*easy-write-procedure*)
  1157. (foreign-string-to-lisp ptr :count data-size))
  1158. data-size) ;@lispcmt{indicates success}
  1159. ;; @lispcmt{The WRITEFUNCTION should return something other than the}
  1160. ;; @lispcmt{#bytes available to signal an error.}
  1161. (error () (if (zerop data-size) 1 0)))))
  1162. @end lisp
  1163. First, note the correlation of the first few forms, used to declare
  1164. the C function's signature, with the signature in C syntax. We
  1165. provide a Lisp name for the function, its return type, and a name and
  1166. type for each argument.
  1167. In the body, we call the dynamically-bound
  1168. @code{*easy-write-procedure*} with a ``finished'' translation, of
  1169. pulling together the raw data and size into a Lisp string, rather than
  1170. deal with the data directly. As part of calling
  1171. @code{curl_easy_perform} later, we'll bind that variable to a closure
  1172. with more useful lexical bindings than the top-level
  1173. @code{defcallback} form.
  1174. Finally, we make a halfhearted effort to prevent non-local exits from
  1175. unwinding the C stack, covering the most likely case with an
  1176. @code{error} handler, which is usually triggered
  1177. unexpectedly.@footnote{Unfortunately, we can't protect against
  1178. @emph{all} non-local exits, such as @code{return}s and @code{throw}s,
  1179. because @code{unwind-protect} cannot be used to ``short-circuit'' a
  1180. non-local exit in Common Lisp, due to proposal @code{minimal} in
  1181. @uref{http://www.lisp.org/HyperSpec/Issues/iss152-writeup.html,
  1182. @acronym{ANSI} issue @sc{Exit-Extent}}. Furthermore, binding an
  1183. @code{error} handler prevents higher-up code from invoking restarts
  1184. that may be provided under the callback's dynamic context. Such is
  1185. the way of compromise.} The reason is that most C code is written to
  1186. understand its own idiosyncratic error condition, implemented above in
  1187. the case of @code{curl_easy_perform}, and more ``undefined behavior''
  1188. can result if we just wipe C stack frames without allowing them to
  1189. execute whatever cleanup actions as they like.
  1190. Using the @code{CURLoption} enumeration in @file{curl.h} once more, we
  1191. can describe the new option by modifying and reevaluating
  1192. @code{define-curl-options}.
  1193. @lisp
  1194. (define-curl-options curl-option
  1195. (long 0 objectpoint 10000 functionpoint 20000 off-t 30000)
  1196. (:noprogress long 43)
  1197. (:nosignal long 99)
  1198. (:errorbuffer objectpoint 10)
  1199. (:url objectpoint 2)
  1200. (:writefunction functionpoint 11)) ;@lispcmt{new item here}
  1201. @end lisp
  1202. Finally, we can use the defined callback and the new
  1203. @code{set-curl-option-writefunction} to finish configuring the easy
  1204. handle, using the @code{callback} macro to retrieve a @cffi{}
  1205. @code{:pointer}, which works like a function pointer in C code.
  1206. @example
  1207. @sc{cffi-user>} (set-curl-option-writefunction
  1208. *easy-handle* (callback easy-write))
  1209. @result{} 0
  1210. @end example
  1211. @node Tutorial-Completion, Tutorial-Types, Tutorial-Callbacks, Tutorial
  1212. @section A complete @acronym{FFI}?
  1213. @c TeX goes insane on @uref{@clikicffi{}}
  1214. With all options finally set and a medium-level interface developed,
  1215. we can finish the definition and retrieve
  1216. @uref{http://www.cliki.net/CFFI}, as is done in the tutorial.
  1217. @lisp
  1218. (defcfun "curl_easy_perform" curl-code
  1219. (handle easy-handle))
  1220. @end lisp
  1221. @example
  1222. @sc{cffi-user>} (with-output-to-string (contents)
  1223. (let ((*easy-write-procedure*
  1224. (lambda (string)
  1225. (write-string string contents))))
  1226. (declare (special *easy-write-procedure*))
  1227. (curl-easy-perform *easy-handle*)))
  1228. @result{} "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"
  1229. @enddots{}
  1230. Now fear, comprehensively</P>
  1231. "
  1232. @end example
  1233. Of course, that itself is slightly unwieldy, so you may want to define
  1234. a function around it that simply retrieves a @acronym{URL}. I will
  1235. leave synthesis of all the relevant @acronym{REPL} forms presented
  1236. thus far into a single function as an exercise for the reader.
  1237. The remaining sections of this tutorial explore some advanced features
  1238. of @cffi{}; the definition of new types will receive special
  1239. attention. Some of these features are essential for particular
  1240. foreign function calls; some are very helpful when trying to develop a
  1241. Lispy interface to C.
  1242. @node Tutorial-Types, Tutorial-Conclusion, Tutorial-Completion, Tutorial
  1243. @section Defining new types
  1244. We've occasionally used the @code{defctype} macro in previous sections
  1245. as a kind of documentation, much what you'd use @code{typedef} for in
  1246. C. We also tried one special kind of type definition, the
  1247. @code{defcenum} type. @xref{defcstruct}, for a definition macro that
  1248. may come in handy if you need to use C @code{struct}s as data.
  1249. @cindex type definition
  1250. @cindex data in Lisp and C
  1251. @cindex translating types
  1252. However, all of these are mostly sugar for the powerful underlying
  1253. foreign type interface called @dfn{type translators}. You can easily
  1254. define new translators for any simple named foreign type. Since we've
  1255. defined the new type @code{curl-code} to use as the return type for
  1256. various @code{libcurl} functions, we can use that to directly convert
  1257. c@acronym{URL} errors to Lisp errors.
  1258. @code{defctype}'s purpose is to define simple @code{typedef}-like
  1259. aliases. In order to use @dfn{type translators} we must use the
  1260. @code{define-foreign-type} macro. So let's redefine @code{curl-code}
  1261. using it.
  1262. @lisp
  1263. (define-foreign-type curl-code-type ()
  1264. ()
  1265. (:actual-type :int)
  1266. (:simple-parser curl-code))
  1267. @end lisp
  1268. @code{define-foreign-type} is a thin wrapper around @code{defclass}.
  1269. For now, all you need to know in the context of this example is that
  1270. it does what @code{(defctype curl-code :int)} would do and,
  1271. additionally, defines a new class @code{curl-code-type} which we will
  1272. take advantage of shortly.
  1273. The @code{CURLcode} enumeration seems to follow the typical error code
  1274. convention of @samp{0} meaning all is well, and each non-zero integer
  1275. indicating a different kind of error. We can apply that trivially to
  1276. differentiate between normal exits and error exits.
  1277. @lisp
  1278. (define-condition curl-code-error (error)
  1279. (($code :initarg :curl-code :reader curl-error-code))
  1280. (:report (lambda (c stream)
  1281. (format stream "libcurl function returned error ~A"
  1282. (curl-error-code c))))
  1283. (:documentation "Signalled when a libcurl function answers
  1284. a code other than CURLE_OK."))
  1285. (defmethod translate-from-foreign (value (type curl-code-type))
  1286. "Raise a CURL-CODE-ERROR if VALUE, a curl-code, is non-zero."
  1287. (if (zerop value)
  1288. :curle-ok
  1289. (error 'curl-code-error :curl-code value)))
  1290. @end lisp
  1291. @noindent
  1292. The heart of this translator is new method
  1293. @code{translate-from-foreign}. By specializing the @var{type}
  1294. parameter on @code{curl-code-type}, we immediately modify the behavior
  1295. of every function that returns a @code{curl-code} to pass the result
  1296. through this new method.
  1297. To see the translator in action, try invoking a function that returns
  1298. a @code{curl-code}. You need to reevaluate the respective
  1299. @code{defcfun} form so that it picks up the new @code{curl-code}
  1300. definition.
  1301. @example
  1302. @sc{cffi-user>} (set-curl-option-nosignal *easy-handle* 1)
  1303. @result{} :CURLE-OK
  1304. @end example
  1305. @noindent
  1306. As the result was @samp{0}, the new method returned @code{:curle-ok},
  1307. just as specified.@footnote{It might be better to return
  1308. @code{(values)} than @code{:curle-ok} in real code, but this is good
  1309. for illustration.} I will leave disjoining the separate
  1310. @code{CURLcode}s into condition types and improving the @code{:report}
  1311. function as an exercise for you.
  1312. The creation of @code{*easy-handle-cstrings*} and
  1313. @code{*easy-handle-errorbuffers*} as properties of @code{easy-handle}s
  1314. is a kluge. What we really want is a Lisp structure that stores these
  1315. properties along with the C pointer. Unfortunately,
  1316. @code{easy-handle} is currently just a fancy name for the foreign type
  1317. @code{:pointer}; the actual pointer object varies from Common Lisp
  1318. implementation to implementation, needing only to satisfy
  1319. @code{pointerp} and be returned from @code{make-pointer} and friends.
  1320. One solution that would allow us to define a new Lisp structure to
  1321. represent @code{easy-handle}s would be to write a wrapper around every
  1322. function that currently takes an @code{easy-handle}; the wrapper would
  1323. extract the pointer and pass it to the foreign function. However, we
  1324. can use type translators to more elegantly integrate this
  1325. ``translation'' into the foreign function calling framework, using
  1326. @code{translate-to-foreign}.
  1327. @smalllisp
  1328. (defclass easy-handle ()
  1329. ((pointer :initform (curl-easy-init)
  1330. :documentation "Foreign pointer from curl_easy_init")
  1331. (error-buffer
  1332. :initform (foreign-alloc :char :count *curl-error-size*
  1333. :initial-element 0)
  1334. :documentation "C string describing last error")
  1335. (c-strings :initform '()
  1336. :documentation "C strings set as options"))
  1337. (:documentation "I am a parameterization you may pass to
  1338. curl-easy-perform to perform a cURL network protocol request."))
  1339. (defmethod initialize-instance :after ((self easy-handle) &key)
  1340. (set-curl-option-errorbuffer self (slot-value self 'error-buffer)))
  1341. (defun add-curl-handle-cstring (handle cstring)
  1342. "Add CSTRING to be freed when HANDLE is, answering CSTRING."
  1343. (car (push cstring (slot-value handle 'c-strings))))
  1344. (defun get-easy-handle-error (handle)
  1345. "Answer a string containing HANDLE's current error message."
  1346. (foreign-string-to-lisp
  1347. (slot-value handle 'error-buffer)))
  1348. (defun free-easy-handle (handle)
  1349. "Free CURL easy interface HANDLE and any C strings created to
  1350. be its options."
  1351. (with-slots (pointer error-buffer c-strings) handle
  1352. (curl-easy-cleanup pointer)
  1353. (foreign-free error-buffer)
  1354. (mapc #'foreign-string-free c-strings)))
  1355. (define-foreign-type easy-handle-type ()
  1356. ()
  1357. (:actual-type :pointer)
  1358. (:simple-parser easy-handle))
  1359. (defmethod translate-to-foreign (handle (type easy-handle-type))
  1360. "Extract the pointer from an easy-HANDLE."
  1361. (slot-value handle 'pointer))
  1362. @end smalllisp
  1363. While we changed some of the Lisp functions defined earlier to use
  1364. @acronym{CLOS} slots rather than hash tables, the foreign functions
  1365. work just as well as they did before.
  1366. @cindex limitations of type translators
  1367. The greatest strength, and the greatest limitation, of the type
  1368. translator comes from its generalized interface. As stated
  1369. previously, we could define all foreign function calls in terms of the
  1370. primitive foreign types provided by @cffi{}. The type translator
  1371. interface allows us to cleanly specify the relationship between Lisp
  1372. and C data, independent of where it appears in a function call. This
  1373. independence comes at a price; for example, it cannot be used to
  1374. modify translation semantics based on other arguments to a function
  1375. call. In these cases, you should rely on other features of Lisp,
  1376. rather than the powerful, yet domain-specific, type translator
  1377. interface.
  1378. @node Tutorial-Conclusion, , Tutorial-Types, Tutorial
  1379. @section What's next?
  1380. @cffi{} provides a rich and powerful foundation for communicating with
  1381. foreign libraries; as we have seen, it is up to you to make that
  1382. experience a pleasantly Lispy one. This tutorial does not cover all
  1383. the features of @cffi{}; please see the rest of the manual for
  1384. details. In particular, if something seems obviously missing, it is
  1385. likely that either code or a good reason for lack of code is already
  1386. present.
  1387. @impnote{There are some other things in @cffi{} that might deserve
  1388. tutorial sections, such as free-translated-object, or structs. Let us
  1389. know which ones you care about.}
  1390. @c ===================================================================
  1391. @c CHAPTER: Wrapper generators
  1392. @node Wrapper generators, Foreign Types, Tutorial, Top
  1393. @chapter Wrapper generators
  1394. @cffi{}'s interface is designed for human programmers, being aimed at
  1395. aesthetic as well as technical sophistication. However, there are a
  1396. few programs aimed at translating C and C++ header files, or
  1397. approximations thereof, into @cffi{} forms constituting a foreign
  1398. interface to the symbols in those files.
  1399. These wrapper generators are known to support output of @cffi{} forms.
  1400. @table @asis
  1401. @item @uref{http://www.cliki.net/Verrazano,Verrazano}
  1402. Designed specifically for Common Lisp. Uses @acronym{GCC}'s parser
  1403. output in @acronym{XML} format to discover functions, variables, and
  1404. other header file data. This means you need @acronym{GCC} to generate
  1405. forms; on the other hand, the parser employed is mostly compliant with
  1406. @acronym{ANSI} C.
  1407. @item @uref{http://www.cliki.net/SWIG,SWIG}
  1408. A foreign interface generator originally designed to generate Python
  1409. bindings, it has been ported to many other systems, including @cffi{}
  1410. in version 1.3.28. Includes its own C declaration munger, not
  1411. intended to be fully-compliant with @acronym{ANSI} C.
  1412. @end table
  1413. First, this manual does not describe use of these other programs; they
  1414. have documentation of their own. If you have problems using a
  1415. generated interface, please look at the output @cffi{} forms and
  1416. verify that they are a correct @cffi{} interface to the library in
  1417. question; if they are correct, contact @cffi{} developers with
  1418. details, keeping in mind that they communicate in terms of those forms
  1419. rather than any particular wrapper generator. Otherwise, contact the
  1420. maintainers of the wrapper generator you are using, provided you can
  1421. reasonably expect more accuracy from the generator.
  1422. When is more accuracy an unreasonable expectation? As described in
  1423. the tutorial (@pxref{Tutorial-Abstraction,, Breaking the
  1424. abstraction}), the information in C declarations is insufficient to
  1425. completely describe every interface. In fact, it is quite common to
  1426. run into an interface that cannot be handled automatically, and
  1427. generators should be excused from generating a complete interface in
  1428. these cases.
  1429. As further described in the tutorial, the thinnest Lisp interface to a
  1430. C function is not always the most pleasant one. In many cases, you
  1431. will want to manually write a Lispier interface to the C functions
  1432. that interest you.
  1433. Wrapper generators should be treated as time-savers, not complete
  1434. automation of the full foreign interface writing job. Reports of the
  1435. amount of work done by generators vary from 30% to 90%. The
  1436. incremental development style enabled by @cffi{} generally reduces
  1437. this proportion below that for languages like Python.
  1438. @c Where I got the above 30-90% figures:
  1439. @c 30%: lemonodor's post about SWIG
  1440. @c 90%: Balooga on #lisp. He said 99%, but that's probably an
  1441. @c exaggeration (leave it to me to pass judgement :)
  1442. @c -stephen
  1443. @c ===================================================================
  1444. @c CHAPTER: Foreign Types
  1445. @node Foreign Types, Pointers, Wrapper generators, Top
  1446. @chapter Foreign Types
  1447. Foreign types describe how data is translated back and forth between C
  1448. and Lisp. @cffi{} provides various built-in types and allows the user to
  1449. define new types.
  1450. @menu
  1451. * Built-In Types::
  1452. * Other Types::
  1453. * Defining Foreign Types::
  1454. * Foreign Type Translators::
  1455. * Optimizing Type Translators::
  1456. * Foreign Structure Types::
  1457. * Allocating Foreign Objects::
  1458. Dictionary
  1459. * convert-from-foreign::
  1460. * convert-to-foreign::
  1461. * defbitfield::
  1462. * defcstruct::
  1463. * defcunion::
  1464. * defctype::
  1465. * defcenum::
  1466. @c * define-type-spec-parser::
  1467. * define-foreign-type::
  1468. * define-parse-method::
  1469. @c * explain-foreign-slot-value:
  1470. * foreign-bitfield-symbols::
  1471. * foreign-bitfield-value::
  1472. * foreign-enum-keyword::
  1473. * foreign-enum-value::
  1474. * foreign-slot-names::
  1475. * foreign-slot-offset::
  1476. * foreign-slot-pointer::
  1477. * foreign-slot-value::
  1478. * foreign-type-alignment::
  1479. * foreign-type-size::
  1480. * free-converted-object::
  1481. * free-translated-object::
  1482. * translate-from-foreign::
  1483. * translate-to-foreign::
  1484. * translate-into-foreign-memory::
  1485. * with-foreign-slots::
  1486. @end menu
  1487. @node Built-In Types, Other Types, Foreign Types, Foreign Types
  1488. @section Built-In Types
  1489. @ForeignType{:char}
  1490. @ForeignType{:unsigned-char}
  1491. @ForeignType{:short}
  1492. @ForeignType{:unsigned-short}
  1493. @ForeignType{:int}
  1494. @ForeignType{:unsigned-int}
  1495. @ForeignType{:long}
  1496. @ForeignType{:unsigned-long}
  1497. @ForeignType{:long-long}
  1498. @ForeignType{:unsigned-long-long}
  1499. These types correspond to the native C integer types according to the
  1500. @acronym{ABI} of the Lisp implementation's host system.
  1501. @code{:long-long} and @code{:unsigned-long-long} are not supported
  1502. natively on all implementations. However, they are emulated by
  1503. @code{mem-ref} and @code{mem-set}.
  1504. When those types are @strong{not} available, the symbol
  1505. @code{cffi-sys::no-long-long} is pushed into @code{*features*}.
  1506. @ForeignType{:uchar}
  1507. @ForeignType{:ushort}
  1508. @ForeignType{:uint}
  1509. @ForeignType{:ulong}
  1510. @ForeignType{:llong}
  1511. @ForeignType{:ullong}
  1512. For convenience, the above types are provided as shortcuts for
  1513. @code{unsigned-char}, @code{unsigned-short}, @code{unsigned-int},
  1514. @code{unsigned-long}, @code{long-long} and @code{unsigned-long-long},
  1515. respectively.
  1516. @ForeignType{:int8}
  1517. @ForeignType{:uint8}
  1518. @ForeignType{:int16}
  1519. @ForeignType{:uint16}
  1520. @ForeignType{:int32}
  1521. @ForeignType{:uint32}
  1522. @ForeignType{:int64}
  1523. @ForeignType{:uint64}
  1524. @ForeignType{:size}
  1525. @ForeignType{:ssize}
  1526. @ForeignType{:intptr}
  1527. @ForeignType{:uintptr}
  1528. @ForeignType{:ptrdiff}
  1529. @ForeignType{:offset}
  1530. Foreign integer types of specific sizes, corresponding to the C types
  1531. defined in @code{stdint.h}.
  1532. @c @ForeignType{:time}
  1533. @c Foreign integer types corresponding to the standard C types (without
  1534. @c the @code{_t} suffix).
  1535. @c @impnote{These are not implemented yet. --luis}
  1536. @c @impnote{I'm sure there are more of these that could be useful, let's
  1537. @c add any types that can't be defined portably to this list as
  1538. @c necessary. --james}
  1539. @ForeignType{:float}
  1540. @ForeignType{:double}
  1541. On all systems, the @code{:float} and @code{:double} types represent a
  1542. C @code{float} and @code{double}, respectively. On most but not all
  1543. systems, @code{:float} and @code{:double} represent a Lisp
  1544. @code{single-float} and @code{double-float}, respectively. It is not
  1545. so useful to consider the relationship between Lisp types and C types
  1546. as isomorphic, as simply to recognize the relationship, and relative
  1547. precision, among each respective category.
  1548. @ForeignType{:long-double}
  1549. This type is only supported on SCL.
  1550. @ForeignType{:pointer &optional type}
  1551. A foreign pointer to an object of any type, corresponding to
  1552. @code{void *}. You can optionally specify type of pointer
  1553. (e.g. @code{(:pointer :char)}). Although @cffi{} won't do anything
  1554. with that information yet, it is useful for documentation purposes.
  1555. @ForeignType{:void}
  1556. No type at all. Only valid as the return type of a function.
  1557. @node Other Types, Defining Foreign Types, Built-In Types, Foreign Types
  1558. @section Other Types
  1559. @cffi{} also provides a few useful types that aren't built-in C
  1560. types.
  1561. @ForeignType{:string}
  1562. The @code{:string} type performs automatic conversion between Lisp and
  1563. C strings. Note that, in the case of functions the converted C string
  1564. will have dynamic extent (i.e.@: it will be automatically freed after
  1565. the foreign function returns).
  1566. In addition to Lisp strings, this type will accept foreign pointers
  1567. and pass them unmodified.
  1568. A method for @ref{free-translated-object} is specialized for this
  1569. type. So, for example, foreign strings allocated by this type and
  1570. passed to a foreign function will be freed after the function
  1571. returns.
  1572. @lisp
  1573. CFFI> (foreign-funcall "getenv" :string "SHELL" :string)
  1574. @result{} "/bin/bash"
  1575. CFFI> (with-foreign-string (str "abcdef")
  1576. (foreign-funcall "strlen" :string str :int))
  1577. @result{} 6
  1578. @end lisp
  1579. @ForeignType{:string+ptr}
  1580. Like @code{:string} but returns a list with two values when convert
  1581. from C to Lisp: a Lisp string and the C string's foreign pointer.
  1582. @lisp
  1583. CFFI> (foreign-funcall "getenv" :string "SHELL" :string+ptr)
  1584. @result{} ("/bin/bash" #.(SB-SYS:INT-SAP #XBFFFFC6F))
  1585. @end lisp
  1586. @ForeignType{:boolean &optional (base-type :int)}
  1587. The @code{:boolean} type converts between a Lisp boolean and a C
  1588. boolean. It canonicalizes to @var{base-type} which is @code{:int} by
  1589. default.
  1590. @lisp
  1591. (convert-to-foreign nil :boolean) @result{} 0
  1592. (convert-to-foreign t :boolean) @result{} 1
  1593. (convert-from-foreign 0 :boolean) @result{} nil
  1594. (convert-from-foreign 1 :boolean) @result{} t
  1595. @end lisp
  1596. @ForeignType{:bool}
  1597. The @code{:bool} type represents the C99 @code{_Bool} or C++
  1598. @code{bool}. Its size is usually 1 byte except on OSX where it's an
  1599. @code{int}.
  1600. @ForeignType{:wrapper base-type &key to-c from-c}
  1601. The @code{:wrapper} type stores two symbols passed to the @var{to-c}
  1602. and @var{from-c} arguments. When a value is being translated to or
  1603. from C, this type @code{funcall}s the respective symbol.
  1604. @code{:wrapper} types will be typedefs for @var{base-type} and will
  1605. inherit its translators, if any.
  1606. Here's an example of how the @code{:boolean} type could be defined in
  1607. terms of @code{:wrapper}.
  1608. @lisp
  1609. (defun bool-c-to-lisp (value)
  1610. (not (zerop value)))
  1611. (defun bool-lisp-to-c (value)
  1612. (if value 1 0))
  1613. (defctype my-bool (:wrapper :int :from-c bool-c-to-lisp
  1614. :to-c bool-lisp-to-c))
  1615. (convert-to-foreign nil 'my-bool) @result{} 0
  1616. (convert-from-foreign 1 'my-bool) @result{} t
  1617. @end lisp
  1618. @node Defining Foreign Types, Foreign Type Translators, Other Types, Foreign Types
  1619. @section Defining Foreign Types
  1620. You can define simple C-like @code{typedef}s through the
  1621. @code{defctype} macro. Defining a typedef is as simple as giving
  1622. @code{defctype} a new name and the name of the type to be wrapped.
  1623. @lisp
  1624. ;;; @lispcmt{Define MY-INT as an alias for the built-in type :INT.}
  1625. (defctype my-int :int)
  1626. @end lisp
  1627. With this type definition, one can, for instance, declare arguments to
  1628. foreign functions as having the type @code{my-int}, and they will be
  1629. passed as integers.
  1630. @subheading More complex types
  1631. @cffi{} offers another way to define types through
  1632. @code{define-foreign-type}, a thin wrapper macro around
  1633. @code{defclass}. As an example, let's go through the steps needed to
  1634. define a @code{(my-string &key encoding)} type. First, we need to
  1635. define our type class:
  1636. @lisp
  1637. (define-foreign-type my-string-type ()
  1638. ((encoding :reader string-type-encoding :initarg :encoding))
  1639. (:actual-type :pointer))
  1640. @end lisp
  1641. The @code{:actual-type} class option tells CFFI that this type will
  1642. ultimately be passed to and received from foreign code as a
  1643. @code{:pointer}. Now you need to tell CFFI how to parse a type
  1644. specification such as @code{(my-string :encoding :utf8)} into an
  1645. instance of @code{my-string-type}. We do that with
  1646. @code{define-parse-method}:
  1647. @lisp
  1648. (define-parse-method my-string (&key (encoding :utf-8))
  1649. (make-instance 'my-string-type :encoding encoding))
  1650. @end lisp
  1651. The next section describes how make this type actually translate
  1652. between C and Lisp strings.
  1653. @node Foreign Type Translators, Optimizing Type Translators, Defining Foreign Types, Foreign Types
  1654. @section Foreign Type Translators
  1655. Type translators are used to automatically convert Lisp values to or
  1656. from foreign values. For example, using type translators, one can
  1657. take the @code{my-string} type defined in the previous section and
  1658. specify that it should:
  1659. @itemize
  1660. @item
  1661. convert C strings to Lisp strings;
  1662. @item
  1663. convert Lisp strings to newly allocated C strings;
  1664. @item
  1665. free said C strings when they are no longer needed.
  1666. @end itemize
  1667. In order to tell @cffi{} how to automatically convert Lisp values to
  1668. foreign values, define a specialized method for the
  1669. @code{translate-to-foreign} generic function:
  1670. @lisp
  1671. ;;; @lispcmt{Define a method that converts Lisp strings to C strings.}
  1672. (defmethod translate-to-foreign (string (type my-string-type))
  1673. (foreign-string-alloc string :encoding (string-type-encoding type)))
  1674. @end lisp
  1675. @noindent
  1676. From now on, whenever an object is passed as a @code{my-string} to a
  1677. foreign function, this method will be invoked to convert the Lisp
  1678. value. To perform the inverse operation, which is needed for functions
  1679. that return a @code{my-string}, specialize the
  1680. @code{translate-from-foreign} generic function in the same manner:
  1681. @lisp
  1682. ;;; @lispcmt{Define a method that converts C strings to Lisp strings.}
  1683. (defmethod translate-from-foreign (pointer (type my-string-type))
  1684. (foreign-string-to-lisp pointer :encoding (string-type-encoding type)))
  1685. @end lisp
  1686. @noindent
  1687. When a @code{translate-to-foreign} method requires allocation of
  1688. foreign memory, you must also define a @code{free-translated-object}
  1689. method to free the memory once the foreign object is no longer needed,
  1690. otherwise you'll be faced with memory leaks. This generic function is
  1691. called automatically by @cffi{} when passing objects to foreign
  1692. functions. Let's do that:
  1693. @lisp
  1694. ;;; @lispcmt{Free strings allocated by translate-to-foreign.}
  1695. (defmethod free-translated-object (pointer (type my-string-type) param)
  1696. (declare (ignore param))
  1697. (foreign-string-free pointer))
  1698. @end lisp
  1699. @noindent
  1700. In this specific example, we don't need the @var{param} argument, so
  1701. we ignore it. See @ref{free-translated-object}, for an explanation of
  1702. its purpose and how you can use it.
  1703. A type translator does not necessarily need to convert the value. For
  1704. example, one could define a typedef for @code{:pointer} that ensures,
  1705. in the @code{translate-to-foreign} method, that the value is not a
  1706. null pointer, signalling an error if a null pointer is passed. This
  1707. would prevent some pointer errors when calling foreign functions that
  1708. cannot handle null pointers.
  1709. @strong{Please note:} these methods are meant as extensible hooks
  1710. only, and you should not call them directly. Use
  1711. @code{convert-to-foreign}, @code{convert-from-foreign} and
  1712. @code{free-converted-object} instead.
  1713. @xref{Tutorial-Types,, Defining new types}, for another example of
  1714. type translators.
  1715. @node Optimizing Type Translators, Foreign Structure Types, Foreign Type Translators, Foreign Types
  1716. @section Optimizing Type Translators
  1717. @cindex type translators, optimizing
  1718. @cindex compiler macros for type translation
  1719. @cindex defining type-translation compiler macros
  1720. Being based on generic functions, the type translation mechanism
  1721. described above can add a bit of overhead. This is usually not
  1722. significant, but we nevertheless provide a way of getting rid of the
  1723. overhead for the cases where it matters.
  1724. A good way to understand this issue is to look at the code generated
  1725. by @code{defcfun}. Consider the following example using the previously
  1726. defined @code{my-string} type:
  1727. @lisp
  1728. CFFI> (macroexpand-1 '(defcfun foo my-string (x my-string)))
  1729. ;; @lispcmt{(simplified, downcased, etc...)}
  1730. (defun foo (x)
  1731. (multiple-value-bind (#:G2019 #:PARAM3149)
  1732. (translate-to-foreign x #<MY-STRING-TYPE @{11ED5A79@}>)
  1733. (unwind-protect
  1734. (translate-from-foreign
  1735. (foreign-funcall "foo" :pointer #:G2019 :pointer)
  1736. #<MY-STRING-TYPE @{11ED5659@}>)
  1737. (free-translated-object #:G2019 #<MY-STRING-TYPE @{11ED51A79@}>
  1738. #:PARAM3149))))
  1739. @end lisp
  1740. @noindent
  1741. In order to get rid of those generic function calls, @cffi{} has
  1742. another set of extensible generic functions that provide functionality
  1743. similar to @acronym{CL}'s compiler macros:
  1744. @code{expand-to-foreign-dyn}, @code{expand-to-foreign} and
  1745. @code{expand-from-foreign}. Here's how one could define a
  1746. @code{my-boolean} with them:
  1747. @lisp
  1748. (define-foreign-type my-boolean-type ()
  1749. ()
  1750. (:actual-type :int)
  1751. (:simple-parser my-boolean))
  1752. (defmethod expand-to-foreign (value (type my-boolean-type))
  1753. `(if ,value 1 0))
  1754. (defmethod expand-from-foreign (value (type my-boolean-type))
  1755. `(not (zerop ,value)))
  1756. @end lisp
  1757. @noindent
  1758. And here's what the macroexpansion of a function using this type would
  1759. look like:
  1760. @lisp
  1761. CFFI> (macroexpand-1 '(defcfun bar my-boolean (x my-boolean)))
  1762. ;; @lispcmt{(simplified, downcased, etc...)}
  1763. (defun bar (x)
  1764. (let ((#:g3182 (if x 1 0)))
  1765. (not (zerop (foreign-funcall "bar" :int #:g3182 :int)))))
  1766. @end lisp
  1767. @noindent
  1768. No generic function overhead.
  1769. Let's go back to our @code{my-string} type. The expansion interface
  1770. has no equivalent of @code{free-translated-object}; you must instead
  1771. define a method on @code{expand-to-foreign-dyn}, the third generic
  1772. function in this interface. This is especially useful when you can
  1773. allocate something much more efficiently if you know the object has
  1774. dynamic extent, as is the case with function calls that don't save the
  1775. relevant allocated arguments.
  1776. This exactly what we need for the @code{my-string} type:
  1777. @lisp
  1778. (defmethod expand-from-foreign (form (type my-string-type))
  1779. `(foreign-string-to-lisp ,form))
  1780. (defmethod expand-to-foreign-dyn (value var body (type my-string-type))
  1781. (let ((encoding (string-type-encoding type)))
  1782. `(with-foreign-string (,var ,value :encoding ',encoding)
  1783. ,@@body)))
  1784. @end lisp
  1785. @noindent
  1786. So let's look at the macro expansion:
  1787. @lisp
  1788. CFFI> (macroexpand-1 '(defcfun foo my-string (x my-string)))
  1789. ;; @lispcmt{(simplified, downcased, etc...)}
  1790. (defun foo (x)
  1791. (with-foreign-string (#:G2021 X :encoding ':utf-8)
  1792. (foreign-string-to-lisp
  1793. (foreign-funcall "foo" :pointer #:g2021 :pointer))))
  1794. @end lisp
  1795. @noindent
  1796. Again, no generic function overhead.
  1797. @subheading Other details
  1798. To short-circuit expansion and use the @code{translate-*} functions
  1799. instead, simply call the next method. Return its result in cases
  1800. where your method cannot generate an appropriate replacement for it.
  1801. This analogous to the @code{&whole form} mechanism compiler macros
  1802. provide.
  1803. The @code{expand-*} methods have precedence over their
  1804. @code{translate-*} counterparts and are guaranteed to be used in
  1805. @code{defcfun}, @code{foreign-funcall}, @code{defcvar} and
  1806. @code{defcallback}. If you define a method on each of the
  1807. @code{expand-*} generic functions, you are guaranteed to have full
  1808. control over the expressions generated for type translation in these
  1809. macros.
  1810. They may or may not be used in other @cffi{} operators that need to
  1811. translate between Lisp and C data; you may only assume that
  1812. @code{expand-*} methods will probably only be called during Lisp
  1813. compilation.
  1814. @code{expand-to-foreign-dyn} has precedence over
  1815. @code{expand-to-foreign} and is only used in @code{defcfun} and
  1816. @code{foreign-funcall}, only making sense in those contexts.
  1817. @strong{Important note:} this set of generic functions is called at
  1818. macroexpansion time. Methods are defined when loaded or evaluated,
  1819. not compiled. You are responsible for ensuring that your
  1820. @code{expand-*} methods are defined when the @code{foreign-funcall} or
  1821. other forms that use them are compiled. One way to do this is to put
  1822. the method definitions earlier in the file and inside an appropriate
  1823. @code{eval-when} form; another way is to always load a separate Lisp
  1824. or @acronym{FASL} file containing your @code{expand-*} definitions
  1825. before compiling files with forms that ought to use them. Otherwise,
  1826. they will not be found and the runtime translators will be used
  1827. instead.
  1828. @node Foreign Structure Types, Allocating Foreign Objects, Optimizing Type Translators, Foreign Types
  1829. @section Foreign Structure Types
  1830. For more involved C types than simple aliases to built-in types, such
  1831. as you can make with @code{defctype}, @cffi{} allows declaration of
  1832. structures and unions with @code{defcstruct} and @code{defcunion}.
  1833. For example, consider this fictional C structure declaration holding
  1834. some personal information:
  1835. @example
  1836. struct person @{
  1837. int number;
  1838. char* reason;
  1839. @};
  1840. @end example
  1841. @noindent
  1842. The equivalent @code{defcstruct} form follows:
  1843. @lisp
  1844. (defcstruct person
  1845. (number :int)
  1846. (reason :string))
  1847. @end lisp
  1848. @c LMH structure translation
  1849. By default, @ref{convert-from-foreign} (and also @ref{mem-ref}) will
  1850. make a plist with slot names as keys, and @ref{convert-to-foreign} will
  1851. translate such a plist to a foreign structure. A user wishing to define
  1852. other translations should use the @code{:class} argument to
  1853. @ref{defcstruct}, and then define methods for
  1854. @ref{translate-from-foreign} and
  1855. @ref{translate-into-foreign-memory} that specialize on this class,
  1856. possibly calling @code{call-next-method} to translate from and to the
  1857. plists rather than provide a direct interface to the foreign object.
  1858. The macro @code{translation-forms-for-class} will generate the forms
  1859. necessary to translate a Lisp class into a foreign structure and vice
  1860. versa.
  1861. @c Write separate function doc section for translation-forms-for-class?
  1862. @c Examples, perhaps taken from the tests?
  1863. Please note that this interface is only for those that must know about
  1864. the values contained in a relevant struct. If the library you are
  1865. interfacing returns an opaque pointer that needs only be passed to
  1866. other C library functions, by all means just use @code{:pointer} or a
  1867. type-safe definition munged together with @code{defctype} and type
  1868. translation. To pass or return a structure by value to a function, load
  1869. the cffi-libffi system and specify the structure as @code{(:struct
  1870. @var{structure-name})}. To pass or return the pointer, you can use
  1871. either @code{:pointer} or @code{(:pointer (:struct
  1872. @var{structure-name}))}.
  1873. @subheading Optimizing translate-into-foreign-memory
  1874. Just like how @ref{translate-from-foreign} had
  1875. @code{expand-from-foreign} to optimize away the generic function call
  1876. and @ref{translate-to-foreign} had the same in
  1877. @code{expand-to-foreign}, @ref{translate-into-foreign-memory} has
  1878. @code{expand-into-foreign-memory}.
  1879. Let's use our @code{person} struct in an example. However, we are
  1880. going to spice it up by using a lisp struct rather than a plist to
  1881. represent the person in lisp.
  1882. First we redefine @code{person} very slightly.
  1883. @lisp
  1884. (defcstruct (person :class c-person)
  1885. (number :int)
  1886. (reason :string))
  1887. @end lisp
  1888. By adding @code{:class} we can specialize the @code{translate-*}
  1889. methods on the type @code{c-person}.
  1890. Next we define a lisp struct to use instead of the plists.
  1891. @lisp
  1892. (defstruct lisp-person
  1893. (number 0 :type integer)
  1894. (reason "" :type string))
  1895. @end lisp
  1896. And now let's define the type translators we know already:
  1897. @lisp
  1898. (defmethod translate-from-foreign (ptr (type c-person))
  1899. (with-foreign-slots ((number reason) ptr (:struct person))
  1900. (make-lisp-person :number number :reason reason)))
  1901. (defmethod expand-from-foreign (ptr (type c-person))
  1902. `(with-foreign-slots ((number reason) ,ptr (:struct person))
  1903. (make-lisp-person :number number :reason reason)))
  1904. (defmethod translate-into-foreign-memory (value (type c-person) ptr)
  1905. (with-foreign-slots ((number reason) ptr (:struct person))
  1906. (setf number (lisp-person-number value)
  1907. reason (lisp-person-reason value))))
  1908. @end lisp
  1909. At this point everything works, we can convert to and from our
  1910. @code{lisp-person} and foreign @code{person}. If we macroexpand
  1911. @lisp
  1912. (setf (mem-aref ptr '(:struct person)) x)
  1913. @end lisp
  1914. we get something like:
  1915. @lisp
  1916. (let ((#:store879 x))
  1917. (translate-into-foreign-memory #:store879 #<c-person person>
  1918. (inc-pointer ptr 0))
  1919. #:store879)
  1920. @end lisp
  1921. Which is good, but now we can do better and get rid of that generic
  1922. function call to @code{translate-into-foreign-memory}.
  1923. @lisp
  1924. (defmethod expand-into-foreign-memory (value (type c-person) ptr)
  1925. `(with-foreign-slots ((number reason) ,ptr (:struct person))
  1926. (setf number (lisp-person-number ,value)
  1927. reason (lisp-person-reason ,value))))
  1928. @end lisp
  1929. Now we can expand again so see the changes:
  1930. @lisp
  1931. ;; this:
  1932. (setf (mem-aref ptr '(:struct person)) x)
  1933. ;; expands to this
  1934. ;; (simplified, downcased, etc..)
  1935. (let ((#:store887 x))
  1936. (with-foreign-slots ((number reason) (inc-pointer ptr 0) (:struct person))
  1937. (setf number (lisp-person-number #:store887)
  1938. reason (lisp-person-reason #:store887))) #:store887)
  1939. @end lisp
  1940. And there we are, no generic function overhead.
  1941. @subheading Compatibility note
  1942. Previous versions of CFFI accepted the
  1943. ``bare'' @var{structure-name} as a type specification, which was
  1944. interpreted as a pointer to the structure. This is deprecated and
  1945. produces a style warning. Using this deprecated form means that
  1946. @ref{mem-aref} retains its prior meaning and returns a pointer. Using
  1947. the @code{(:struct @var{structure-name})} form for the type,
  1948. @ref{mem-aref} provides a Lisp object translated from the
  1949. structure (by default a plist). Thus the semantics are consistent with all
  1950. types in returning the object as represented in Lisp, and not a pointer,
  1951. with the exception of the ``bare'' structure compatibility retained.
  1952. In order to obtain the pointer, you should use the function @ref{mem-aptr}.
  1953. See @ref{defcstruct} for more details.
  1954. @node Allocating Foreign Objects, convert-from-foreign, Foreign Structure Types, Foreign Types
  1955. @section Allocating Foreign Objects
  1956. @c I moved this because I moved with-foreign-object to the Pointers
  1957. @c chapter, where foreign-alloc is.
  1958. @xref{Allocating Foreign Memory}.
  1959. @c ===================================================================
  1960. @c CONVERT-FROM-FOREIGN
  1961. @page
  1962. @node convert-from-foreign, convert-to-foreign, Allocating Foreign Objects, Foreign Types
  1963. @heading convert-from-foreign
  1964. @subheading Syntax
  1965. @Function{convert-from-foreign foreign-value type @res{} value}
  1966. @subheading Arguments and Values
  1967. @table @var
  1968. @item foreign-value
  1969. The primitive C value as returned from a primitive foreign function or
  1970. from @code{convert-to-foreign}.
  1971. @item type
  1972. A @cffi{} type specifier.
  1973. @item value
  1974. The Lisp value translated from @var{foreign-value}.
  1975. @end table
  1976. @subheading Description
  1977. This is an external interface to the type translation facility. In
  1978. the implementation, all foreign functions are ultimately defined as
  1979. type translation wrappers around primitive foreign function
  1980. invocations.
  1981. This function is available mostly for inspection of the type
  1982. translation process, and possibly optimization of special cases of
  1983. your foreign function calls.
  1984. Its behavior is better described under @code{translate-from-foreign}'s
  1985. documentation.
  1986. @subheading Examples
  1987. @lisp
  1988. CFFI-USER> (convert-to-foreign "a boat" :string)
  1989. @result{} #<FOREIGN-ADDRESS #x097ACDC0>
  1990. @result{} T
  1991. CFFI-USER> (convert-from-foreign * :string)
  1992. @result{} "a boat"
  1993. @end lisp
  1994. @subheading See Also
  1995. @seealso{convert-to-foreign} @*
  1996. @seealso{free-converted-object} @*
  1997. @seealso{translate-from-foreign}
  1998. @c ===================================================================
  1999. @c CONVERT-TO-FOREIGN
  2000. @page
  2001. @node convert-to-foreign, defbitfield, convert-from-foreign, Foreign Types
  2002. @heading convert-to-foreign
  2003. @subheading Syntax
  2004. @Function{convert-to-foreign value type @res{} foreign-value, alloc-params}
  2005. @subheading Arguments and Values
  2006. @table @var
  2007. @item value
  2008. The Lisp object to be translated to a foreign object.
  2009. @item type
  2010. A @cffi{} type specifier.
  2011. @item foreign-value
  2012. The primitive C value, ready to be passed to a primitive foreign
  2013. function.
  2014. @item alloc-params
  2015. Something of a translation state; you must pass it to
  2016. @code{free-converted-object} along with the foreign value for that to
  2017. work.
  2018. @end table
  2019. @subheading Description
  2020. This is an external interface to the type translation facility. In
  2021. the implementation, all foreign functions are ultimately defined as
  2022. type translation wrappers around primitive foreign function
  2023. invocations.
  2024. This function is available mostly for inspection of the type
  2025. translation process, and possibly optimization of special cases of
  2026. your foreign function calls.
  2027. Its behavior is better described under @code{translate-to-foreign}'s
  2028. documentation.
  2029. @subheading Examples
  2030. @lisp
  2031. CFFI-USER> (convert-to-foreign t :boolean)
  2032. @result{} 1
  2033. @result{} NIL
  2034. CFFI-USER> (convert-to-foreign "hello, world" :string)
  2035. @result{} #<FOREIGN-ADDRESS #x097C5F80>
  2036. @result{} T
  2037. CFFI-USER> (code-char (mem-aref * :char 5))
  2038. @result{} #\,
  2039. @end lisp
  2040. @subheading See Also
  2041. @seealso{convert-from-foreign} @*
  2042. @seealso{free-converted-object} @*
  2043. @seealso{translate-to-foreign}
  2044. @c ===================================================================
  2045. @c DEFBITFIELD
  2046. @page
  2047. @node defbitfield, defcstruct, convert-to-foreign, Foreign Types
  2048. @heading defbitfield
  2049. @subheading Syntax
  2050. @Macro{defbitfield name-and-options &body masks}
  2051. masks ::= [docstring] @{ (symbol value) @}* @*
  2052. name-and-options ::= name | (name &optional (base-type :int)) @*
  2053. @subheading Arguments and Values
  2054. @table @var
  2055. @item name
  2056. The name of the new bitfield type.
  2057. @item docstring
  2058. A documentation string, ignored.
  2059. @item base-type
  2060. A symbol denoting a foreign type.
  2061. @item symbol
  2062. A Lisp symbol.
  2063. @item value
  2064. An integer representing a bitmask.
  2065. @end table
  2066. @subheading Description
  2067. The @code{defbitfield} macro is used to define foreign types that map
  2068. lists of symbols to integer values.
  2069. If @var{value} is omitted, it will be computed as follows: find the
  2070. greatest @var{value} previously used, including those so computed,
  2071. with only a single 1-bit in its binary representation (that is, powers
  2072. of two), and left-shift it by one. This rule guarantees that a
  2073. computed @var{value} cannot clash with previous values, but may clash
  2074. with future explicitly specified values.
  2075. Symbol lists will be automatically converted to values and vice versa
  2076. when being passed as arguments to or returned from foreign functions,
  2077. respectively. The same applies to any other situations where an object
  2078. of a bitfield type is expected.
  2079. Types defined with @code{defbitfield} canonicalize to @var{base-type}
  2080. which is @code{:int} by default.
  2081. @subheading Examples
  2082. @lisp
  2083. (defbitfield open-flags
  2084. (:rdonly #x0000)
  2085. :wronly ;@lispcmt{#x0001}
  2086. :rdwr ;@lispcmt{@dots{}}
  2087. :nonblock
  2088. :append
  2089. (:creat #x0200))
  2090. ;; @lispcmt{etc@dots{}}
  2091. CFFI> (foreign-bitfield-symbols 'open-flags #b1101)
  2092. @result{} (:WRONLY :NONBLOCK :APPEND)
  2093. CFFI> (foreign-bitfield-value 'open-flags '(:rdwr :creat))
  2094. @result{} 514 ; #x0202
  2095. (defcfun ("open" unix-open) :int
  2096. (path :string)
  2097. (flags open-flags)
  2098. (mode :uint16)) ; unportable
  2099. CFFI> (unix-open "/tmp/foo" '(:wronly :creat) #o644)
  2100. @result{} #<an fd>
  2101. ;;; @lispcmt{Consider also the following lispier wrapper around open()}
  2102. (defun lispier-open (path mode &rest flags)
  2103. (unix-open path flags mode))
  2104. @end lisp
  2105. @subheading See Also
  2106. @seealso{foreign-bitfield-value} @*
  2107. @seealso{foreign-bitfield-symbols}
  2108. @c ===================================================================
  2109. @c DEFCSTRUCT
  2110. @page
  2111. @node defcstruct, defcunion, defbitfield, Foreign Types
  2112. @heading defcstruct
  2113. @subheading Syntax
  2114. @Macro{defcstruct name-and-options &body doc-and-slots @res{} name}
  2115. name-and-options ::= structure-name | (structure-name &key size) @*
  2116. doc-and-slots ::= [docstring] @{ (slot-name slot-type &key count offset) @}*
  2117. @subheading Arguments and Values
  2118. @table @var
  2119. @item structure-name
  2120. The name of new structure type.
  2121. @item docstring
  2122. A documentation string, ignored.
  2123. @item slot-name
  2124. A symbol naming the slot. It must be unique among slot names in this
  2125. structure.
  2126. @item size
  2127. Use this option to override the size (in bytes) of the struct.
  2128. @item slot-type
  2129. The type specifier for the slot.
  2130. @item count
  2131. Used to declare an array of size @var{count} inside the
  2132. structure. Defaults to @code{1} as such an array and a single element
  2133. are semantically equivalent.
  2134. @item offset
  2135. Overrides the slot's offset. The next slot's offset is calculated
  2136. based on this one.
  2137. @end table
  2138. @subheading Description
  2139. This defines a new @cffi{} aggregate type akin to C @code{struct}s.
  2140. In other words, it specifies that foreign objects of the type
  2141. @var{structure-name} are groups of different pieces of data, or
  2142. ``slots'', of the @var{slot-type}s, distinguished from each other by
  2143. the @var{slot-name}s. Each structure is located in memory at a
  2144. position, and the slots are allocated sequentially beginning at that
  2145. point in memory (with some padding allowances as defined by the C
  2146. @acronym{ABI}, unless otherwise requested by specifying an
  2147. @var{offset} from the beginning of the structure (offset 0).
  2148. In other words, it is isomorphic to the C @code{struct}, giving
  2149. several extra features.
  2150. There are two kinds of slots, for the two kinds of @cffi{} types:
  2151. @table @dfn
  2152. @item Simple
  2153. Contain a single instance of a type that canonicalizes to a built-in
  2154. type, such as @code{:long} or @code{:pointer}. Used for simple
  2155. @cffi{} types.
  2156. @item Aggregate
  2157. Contain an embedded structure or union, or an array of objects. Used
  2158. for aggregate @cffi{} types.
  2159. @end table
  2160. The use of @acronym{CLOS} terminology for the structure-related
  2161. features is intentional; structure definitions are very much like
  2162. classes with (far) fewer features.
  2163. @subheading Examples
  2164. @lisp
  2165. (defcstruct point
  2166. "Point structure."
  2167. (x :int)
  2168. (y :int))
  2169. CFFI> (with-foreign-object (ptr 'point)
  2170. ;; @lispcmt{Initialize the slots}
  2171. (setf (foreign-slot-value ptr 'point 'x) 42
  2172. (foreign-slot-value ptr 'point 'y) 42)
  2173. ;; @lispcmt{Return a list with the coordinates}
  2174. (with-foreign-slots ((x y) ptr point)
  2175. (list x y)))
  2176. @result{} (42 42)
  2177. @end lisp
  2178. @lisp
  2179. ;; @lispcmt{Using the :size and :offset options to define a partial structure.}
  2180. ;; @lispcmt{(this is useful when you are interested in only a few slots}
  2181. ;; @lispcmt{of a big foreign structure)}
  2182. (defcstruct (foo :size 32)
  2183. "Some struct with 32 bytes."
  2184. ; @lispcmt{<16 bytes we don't care about>}
  2185. (x :int :offset 16) ; @lispcmt{an int at offset 16}
  2186. (y :int) ; @lispcmt{another int at offset 16+sizeof(int)}
  2187. ; @lispcmt{<a couple more bytes we don't care about>}
  2188. (z :char :offset 24)) ; @lispcmt{a char at offset 24}
  2189. ; @lispcmt{<7 more bytes ignored (since size is 32)>}
  2190. CFFI> (foreign-type-size 'foo)
  2191. @result{} 32
  2192. @end lisp
  2193. @lisp
  2194. ;;; @lispcmt{Using :count to define arrays inside of a struct.}
  2195. (defcstruct video_tuner
  2196. (name :char :count 32))
  2197. @end lisp
  2198. @subheading See Also
  2199. @seealso{foreign-slot-pointer} @*
  2200. @seealso{foreign-slot-value} @*
  2201. @seealso{with-foreign-slots}
  2202. @c ===================================================================
  2203. @c DEFCUNION
  2204. @page
  2205. @node defcunion, defctype, defcstruct, Foreign Types
  2206. @heading defcunion
  2207. @subheading Syntax
  2208. @Macro{defcunion name &body doc-and-slots @res{} name}
  2209. doc-and-slots ::= [docstring] @{ (slot-name slot-type &key count) @}*
  2210. @subheading Arguments and Values
  2211. @table @var
  2212. @item name
  2213. The name of new union type.
  2214. @item docstring
  2215. A documentation string, ignored.
  2216. @item slot-name
  2217. A symbol naming the slot.
  2218. @item slot-type
  2219. The type specifier for the slot.
  2220. @item count
  2221. Used to declare an array of size @var{count} inside the
  2222. structure.
  2223. @end table
  2224. @subheading Description
  2225. A union is a structure in which all slots have an offset of zero. It
  2226. is isomorphic to the C @code{union}. Therefore, you should use the
  2227. usual foreign structure operations for accessing a union's slots.
  2228. @subheading Examples
  2229. @lisp
  2230. (defcunion uint32-bytes
  2231. (int-value :unsigned-int)
  2232. (bytes :unsigned-char :count 4))
  2233. @end lisp
  2234. @subheading See Also
  2235. @seealso{foreign-slot-pointer} @*
  2236. @seealso{foreign-slot-value}
  2237. @c ===================================================================
  2238. @c DEFCTYPE
  2239. @page
  2240. @node defctype, defcenum, defcunion, Foreign Types
  2241. @heading defctype
  2242. @subheading Syntax
  2243. @Macro{defctype name base-type &optional documentation}
  2244. @subheading Arguments and Values
  2245. @table @var
  2246. @item name
  2247. The name of the new foreign type.
  2248. @item base-type
  2249. A symbol or a list defining the new type.
  2250. @item documentation
  2251. A documentation string, currently ignored.
  2252. @end table
  2253. @subheading Description
  2254. The @code{defctype} macro provides a mechanism similar to C's
  2255. @code{typedef} to define new types. The new type inherits
  2256. @var{base-type}'s translators, if any. There is no way to define
  2257. translations for types defined with @code{defctype}. For that,
  2258. you should use @ref{define-foreign-type}.
  2259. @subheading Examples
  2260. @lisp
  2261. (defctype my-string :string
  2262. "My own string type.")
  2263. (defctype long-bools (:boolean :long)
  2264. "Booleans that map to C longs.")
  2265. @end lisp
  2266. @subheading See Also
  2267. @seealso{define-foreign-type}
  2268. @c ===================================================================
  2269. @c DEFCENUM
  2270. @page
  2271. @node defcenum, define-foreign-type, defctype, Foreign Types
  2272. @heading defcenum
  2273. @subheading Syntax
  2274. @Macro{defcenum name-and-options &body enum-list}
  2275. enum-list ::= [docstring] @{ keyword | (keyword value) @}* @*
  2276. name-and-options ::= name | (name &optional (base-type :int) &key allow-undeclared-values) @*
  2277. @subheading Arguments and Values
  2278. @table @var
  2279. @item name
  2280. The name of the new enum type.
  2281. @item docstring
  2282. A documentation string, ignored.
  2283. @item base-type
  2284. A symbol denoting a foreign type.
  2285. @item allow-undeclared-values
  2286. Whether to pass through integer values that were not explicitly declared
  2287. in the enum when translating from foreign memory.
  2288. @item keyword
  2289. A keyword symbol.
  2290. @item value
  2291. An index value for a keyword.
  2292. @end table
  2293. @subheading Description
  2294. The @code{defcenum} macro is used to define foreign types that map
  2295. keyword symbols to integer values, similar to the C @code{enum} type.
  2296. If @var{value} is omitted its value will either be 0, if it's the
  2297. first entry, or it it will continue the progression from the last
  2298. specified value.
  2299. Keywords will be automatically converted to values and vice-versa when
  2300. being passed as arguments to or returned from foreign functions,
  2301. respectively. The same applies to any other situations where an object
  2302. of an @code{enum} type is expected.
  2303. If a value should be translated to lisp that is not declared in the
  2304. enum, an error will be signalled. You can elide this error and instead
  2305. make it pass the original enum value by specifying
  2306. @var{allow-undeclared-values}. This can be useful for very large
  2307. enumerations of which we only care about a subset of values, or for
  2308. enumerations that should allow for client or vendor extensions that we
  2309. cannot know about.
  2310. Types defined with @code{defcenum} canonicalize to @var{base-type}
  2311. which is @code{:int} by default.
  2312. @subheading Examples
  2313. @lisp
  2314. (defcenum boolean
  2315. :no
  2316. :yes)
  2317. CFFI> (foreign-enum-value 'boolean :no)
  2318. @result{} 0
  2319. @end lisp
  2320. @lisp
  2321. (defcenum numbers
  2322. (:one 1)
  2323. :two
  2324. (:four 4))
  2325. CFFI> (foreign-enum-keyword 'numbers 2)
  2326. @result{} :TWO
  2327. @end lisp
  2328. @subheading See Also
  2329. @seealso{foreign-enum-value} @*
  2330. @seealso{foreign-enum-keyword}
  2331. @c ===================================================================
  2332. @c DEFINE-FOREIGN-TYPE
  2333. @page
  2334. @node define-foreign-type, define-parse-method, defcenum, Foreign Types
  2335. @heading define-foreign-type
  2336. @subheading Syntax
  2337. @Macro{define-foreign-type class-name supers slots &rest options @res{} class-name}
  2338. options ::= (@code{:actual-type} @var{type}) | @
  2339. (@code{:simple-parser} @var{symbol}) | @
  2340. @emph{regular defclass option}
  2341. @subheading Arguments and Values
  2342. @table @var
  2343. @item class-name
  2344. A symbol naming the new foreign type class.
  2345. @item supers
  2346. A list of symbols naming the super classes.
  2347. @item slots
  2348. A list of slot definitions, passed to @code{defclass}.
  2349. @end table
  2350. @subheading Description
  2351. @c TODO rewrite
  2352. The macro @code{define-foreign-type} defines a new class
  2353. @var{class-name}. It is a thin wrapper around @code{defclass}. Among
  2354. other things, it ensures that @var{class-name} becomes a subclass of
  2355. @var{foreign-type}, what you need to know about that is that there's
  2356. an initarg @code{:actual-type} which serves the same purpose as
  2357. @code{defctype}'s @var{base-type} argument.
  2358. @c TODO mention the type translators here
  2359. @c FIX FIX
  2360. @subheading Examples
  2361. Taken from @cffi{}'s @code{:boolean} type definition:
  2362. @lisp
  2363. (define-foreign-type :boolean (&optional (base-type :int))
  2364. "Boolean type. Maps to an :int by default. Only accepts integer types."
  2365. (ecase base-type
  2366. ((:char
  2367. :unsigned-char
  2368. :int
  2369. :unsigned-int
  2370. :long
  2371. :unsigned-long) base-type)))
  2372. CFFI> (canonicalize-foreign-type :boolean)
  2373. @result{} :INT
  2374. CFFI> (canonicalize-foreign-type '(:boolean :long))
  2375. @result{} :LONG
  2376. CFFI> (canonicalize-foreign-type '(:boolean :float))
  2377. ;; @lispcmt{@error{} signalled by ECASE.}
  2378. @end lisp
  2379. @subheading See Also
  2380. @seealso{defctype} @*
  2381. @seealso{define-parse-method}
  2382. @c ===================================================================
  2383. @c DEFINE-PARSE-METHOD
  2384. @page
  2385. @node define-parse-method, foreign-bitfield-symbols, define-foreign-type, Foreign Types
  2386. @heading define-parse-method
  2387. @subheading Syntax
  2388. @Macro{define-parse-method name lambda-list &body body @res{} name}
  2389. @subheading Arguments and Values
  2390. @table @var
  2391. @item type-name
  2392. A symbol naming the new foreign type.
  2393. @item lambda-list
  2394. A lambda list which is the argument list of the new foreign type.
  2395. @item body
  2396. One or more forms that provide a definition of the new foreign type.
  2397. @end table
  2398. @subheading Description
  2399. @c TODO: update example. The boolean type is probably a good choice.
  2400. @subheading Examples
  2401. Taken from @cffi{}'s @code{:boolean} type definition:
  2402. @lisp
  2403. (define-foreign-type :boolean (&optional (base-type :int))
  2404. "Boolean type. Maps to an :int by default. Only accepts integer types."
  2405. (ecase base-type
  2406. ((:char
  2407. :unsigned-char
  2408. :int
  2409. :unsigned-int
  2410. :long
  2411. :unsigned-long) base-type)))
  2412. CFFI> (canonicalize-foreign-type :boolean)
  2413. @result{} :INT
  2414. CFFI> (canonicalize-foreign-type '(:boolean :long))
  2415. @result{} :LONG
  2416. CFFI> (canonicalize-foreign-type '(:boolean :float))
  2417. ;; @lispcmt{@error{} signalled by ECASE.}
  2418. @end lisp
  2419. @subheading See Also
  2420. @seealso{define-foreign-type}
  2421. @c ===================================================================
  2422. @c EXPLAIN-FOREIGN-SLOT-VALUE
  2423. @c @node explain-foreign-slot-value
  2424. @c @heading explain-foreign-slot-value
  2425. @c @subheading Syntax
  2426. @c @Macro{explain-foreign-slot-value ptr type &rest slot-names}
  2427. @c @subheading Arguments and Values
  2428. @c @table @var
  2429. @c @item ptr
  2430. @c ...
  2431. @c @item type
  2432. @c ...
  2433. @c @item slot-names
  2434. @c ...
  2435. @c @end table
  2436. @c @subheading Description
  2437. @c This macro translates the slot access that would occur by calling
  2438. @c @code{foreign-slot-value} with the same arguments into an equivalent
  2439. @c expression in C and prints it to @code{*standard-output*}.
  2440. @c @emph{Note: this is not implemented yet.}
  2441. @c @subheading Examples
  2442. @c @lisp
  2443. @c CFFI> (explain-foreign-slot-value ptr 'timeval 'tv-secs)
  2444. @c @result{} ptr->tv_secs
  2445. @c CFFI> (explain-foreign-slot-value emp 'employee 'hire-date 'tv-usecs)
  2446. @c @result{} emp->hire_date.tv_usecs
  2447. @c @end lisp
  2448. @c @subheading See Also
  2449. @c ===================================================================
  2450. @c FOREIGN-BITFIELD-SYMBOLS
  2451. @page
  2452. @node foreign-bitfield-symbols, foreign-bitfield-value, define-parse-method, Foreign Types
  2453. @heading foreign-bitfield-symbols
  2454. @subheading Syntax
  2455. @Function{foreign-bitfield-symbols type value @res{} symbols}
  2456. @subheading Arguments and Values
  2457. @table @var
  2458. @item type
  2459. A bitfield type.
  2460. @item value
  2461. An integer.
  2462. @item symbols
  2463. A potentially shared list of symbols.
  2464. @code{nil}.
  2465. @end table
  2466. @subheading Description
  2467. The function @code{foreign-bitfield-symbols} returns a possibly shared
  2468. list of symbols that correspond to @var{value} in @var{type}.
  2469. @subheading Examples
  2470. @lisp
  2471. (defbitfield flags
  2472. (flag-a 1)
  2473. (flag-b 2)
  2474. (flag-c 4))
  2475. CFFI> (foreign-bitfield-symbols 'flags #b101)
  2476. @result{} (FLAG-A FLAG-C)
  2477. @end lisp
  2478. @subheading See Also
  2479. @seealso{defbitfield} @*
  2480. @seealso{foreign-bitfield-value}
  2481. @c ===================================================================
  2482. @c FOREIGN-BITFIELD-VALUE
  2483. @page
  2484. @node foreign-bitfield-value, foreign-enum-keyword, foreign-bitfield-symbols, Foreign Types
  2485. @heading foreign-bitfield-value
  2486. @subheading Syntax
  2487. @Function{foreign-bitfield-value type symbols @res{} value}
  2488. @subheading Arguments and Values
  2489. @table @var
  2490. @item type
  2491. A @code{bitfield} type.
  2492. @item symbol
  2493. A Lisp symbol.
  2494. @item value
  2495. An integer.
  2496. @end table
  2497. @subheading Description
  2498. The function @code{foreign-bitfield-value} returns the @var{value} that
  2499. corresponds to the symbols in the @var{symbols} list.
  2500. @subheading Examples
  2501. @lisp
  2502. (defbitfield flags
  2503. (flag-a 1)
  2504. (flag-b 2)
  2505. (flag-c 4))
  2506. CFFI> (foreign-bitfield-value 'flags '(flag-a flag-c))
  2507. @result{} 5 ; #b101
  2508. @end lisp
  2509. @subheading See Also
  2510. @seealso{defbitfield} @*
  2511. @seealso{foreign-bitfield-symbols}
  2512. @c ===================================================================
  2513. @c FOREIGN-ENUM-KEYWORD
  2514. @page
  2515. @node foreign-enum-keyword, foreign-enum-value, foreign-bitfield-value, Foreign Types
  2516. @heading foreign-enum-keyword
  2517. @subheading Syntax
  2518. @Function{foreign-enum-keyword type value &key errorp @res{} keyword}
  2519. @subheading Arguments and Values
  2520. @table @var
  2521. @item type
  2522. An @code{enum} type.
  2523. @item value
  2524. An integer.
  2525. @item errorp
  2526. If true (the default), signal an error if @var{value} is not defined
  2527. in @var{type}. If false, @code{foreign-enum-keyword} returns
  2528. @code{nil}.
  2529. @item keyword
  2530. A keyword symbol.
  2531. @end table
  2532. @subheading Description
  2533. The function @code{foreign-enum-keyword} returns the keyword symbol
  2534. that corresponds to @var{value} in @var{type}.
  2535. An error is signaled if @var{type} doesn't contain such @var{value}
  2536. and @var{errorp} is true.
  2537. @subheading Examples
  2538. @lisp
  2539. (defcenum boolean
  2540. :no
  2541. :yes)
  2542. CFFI> (foreign-enum-keyword 'boolean 1)
  2543. @result{} :YES
  2544. @end lisp
  2545. @subheading See Also
  2546. @seealso{defcenum} @*
  2547. @seealso{foreign-enum-value}
  2548. @c ===================================================================
  2549. @c FOREIGN-ENUM-VALUE
  2550. @page
  2551. @node foreign-enum-value, foreign-slot-names, foreign-enum-keyword, Foreign Types
  2552. @heading foreign-enum-value
  2553. @subheading Syntax
  2554. @Function{foreign-enum-value type keyword &key errorp @res{} value}
  2555. @subheading Arguments and Values
  2556. @table @var
  2557. @item type
  2558. An @code{enum} type.
  2559. @item keyword
  2560. A keyword symbol.
  2561. @item errorp
  2562. If true (the default), signal an error if @var{keyword} is not
  2563. defined in @var{type}. If false, @code{foreign-enum-value} returns
  2564. @code{nil}.
  2565. @item value
  2566. An integer.
  2567. @end table
  2568. @subheading Description
  2569. The function @code{foreign-enum-value} returns the @var{value} that
  2570. corresponds to @var{keyword} in @var{type}.
  2571. An error is signaled if @var{type} doesn't contain such
  2572. @var{keyword}, and @var{errorp} is true.
  2573. @subheading Examples
  2574. @lisp
  2575. (defcenum boolean
  2576. :no
  2577. :yes)
  2578. CFFI> (foreign-enum-value 'boolean :yes)
  2579. @result{} 1
  2580. @end lisp
  2581. @subheading See Also
  2582. @seealso{defcenum} @*
  2583. @seealso{foreign-enum-keyword}
  2584. @c ===================================================================
  2585. @c FOREIGN-SLOT-NAMES
  2586. @page
  2587. @node foreign-slot-names, foreign-slot-offset, foreign-enum-value, Foreign Types
  2588. @heading foreign-slot-names
  2589. @subheading Syntax
  2590. @Function{foreign-slot-names type @res{} names}
  2591. @subheading Arguments and Values
  2592. @table @var
  2593. @item type
  2594. A foreign struct type.
  2595. @item names
  2596. A list.
  2597. @end table
  2598. @subheading Description
  2599. The function @code{foreign-slot-names} returns a potentially shared
  2600. list of slot @var{names} for the given structure @var{type}. This list
  2601. has no particular order.
  2602. @subheading Examples
  2603. @lisp
  2604. (defcstruct timeval
  2605. (tv-secs :long)
  2606. (tv-usecs :long))
  2607. CFFI> (foreign-slot-names '(:struct timeval))
  2608. @result{} (TV-SECS TV-USECS)
  2609. @end lisp
  2610. @subheading See Also
  2611. @seealso{defcstruct} @*
  2612. @seealso{foreign-slot-offset} @*
  2613. @seealso{foreign-slot-value} @*
  2614. @seealso{foreign-slot-pointer}
  2615. @c ===================================================================
  2616. @c FOREIGN-SLOT-OFFSET
  2617. @page
  2618. @node foreign-slot-offset, foreign-slot-pointer, foreign-slot-names, Foreign Types
  2619. @heading foreign-slot-offset
  2620. @subheading Syntax
  2621. @Function{foreign-slot-offset type slot-name @res{} offset}
  2622. @subheading Arguments and Values
  2623. @table @var
  2624. @item type
  2625. A foreign struct type.
  2626. @item slot-name
  2627. A symbol.
  2628. @item offset
  2629. An integer.
  2630. @end table
  2631. @subheading Description
  2632. The function @code{foreign-slot-offset} returns the @var{offset} in
  2633. bytes of a slot in a foreign struct type.
  2634. @subheading Examples
  2635. @lisp
  2636. (defcstruct timeval
  2637. (tv-secs :long)
  2638. (tv-usecs :long))
  2639. CFFI> (foreign-slot-offset '(:struct timeval) 'tv-secs)
  2640. @result{} 0
  2641. CFFI> (foreign-slot-offset '(:struct timeval) 'tv-usecs)
  2642. @result{} 4
  2643. @end lisp
  2644. @subheading See Also
  2645. @seealso{defcstruct} @*
  2646. @seealso{foreign-slot-names} @*
  2647. @seealso{foreign-slot-pointer} @*
  2648. @seealso{foreign-slot-value}
  2649. @c ===================================================================
  2650. @c FOREIGN-SLOT-POINTER
  2651. @page
  2652. @node foreign-slot-pointer, foreign-slot-value, foreign-slot-offset, Foreign Types
  2653. @heading foreign-slot-pointer
  2654. @subheading Syntax
  2655. @Function{foreign-slot-pointer ptr type slot-name @res{} pointer}
  2656. @subheading Arguments and Values
  2657. @table @var
  2658. @item ptr
  2659. A pointer to a structure.
  2660. @item type
  2661. A foreign structure type.
  2662. @item slot-names
  2663. A slot name in the @var{type}.
  2664. @item pointer
  2665. A pointer to the slot @var{slot-name}.
  2666. @end table
  2667. @subheading Description
  2668. Returns a pointer to the location of the slot @var{slot-name} in a
  2669. foreign object of type @var{type} at @var{ptr}. The returned pointer
  2670. points inside the structure. Both the pointer and the memory it points
  2671. to have the same extent as @var{ptr}.
  2672. For aggregate slots, this is the same value returned by
  2673. @code{foreign-slot-value}.
  2674. @subheading Examples
  2675. @lisp
  2676. (defcstruct point
  2677. "Pointer structure."
  2678. (x :int)
  2679. (y :int))
  2680. CFFI> (with-foreign-object (ptr '(:struct point))
  2681. (foreign-slot-pointer ptr '(:struct point) 'x))
  2682. @result{} #<FOREIGN-ADDRESS #xBFFF6E60>
  2683. ;; @lispcmt{Note: the exact pointer representation varies from lisp to lisp.}
  2684. @end lisp
  2685. @subheading See Also
  2686. @seealso{defcstruct} @*
  2687. @seealso{foreign-slot-value} @*
  2688. @seealso{foreign-slot-names} @*
  2689. @seealso{foreign-slot-offset}
  2690. @c ===================================================================
  2691. @c FOREIGN-SLOT-VALUE
  2692. @page
  2693. @node foreign-slot-value, foreign-type-alignment, foreign-slot-pointer, Foreign Types
  2694. @heading foreign-slot-value
  2695. @subheading Syntax
  2696. @Accessor{foreign-slot-value ptr type slot-name @res{} object}
  2697. @subheading Arguments and Values
  2698. @table @var
  2699. @item ptr
  2700. A pointer to a structure.
  2701. @item type
  2702. A foreign structure type.
  2703. @item slot-name
  2704. A symbol naming a slot in the structure type.
  2705. @item object
  2706. The object contained in the slot specified by @var{slot-name}.
  2707. @end table
  2708. @subheading Description
  2709. For simple slots, @code{foreign-slot-value} returns the value of the
  2710. object, such as a Lisp integer or pointer. In C, this would be
  2711. expressed as @code{ptr->slot}.
  2712. For aggregate slots, a pointer inside the structure to the beginning
  2713. of the slot's data is returned. In C, this would be expressed as
  2714. @code{&ptr->slot}. This pointer and the memory it points to have the
  2715. same extent as @var{ptr}.
  2716. There are compiler macros for @code{foreign-slot-value} and its
  2717. @code{setf} expansion that open code the memory access when
  2718. @var{type} and @var{slot-names} are constant at compile-time.
  2719. @subheading Examples
  2720. @lisp
  2721. (defcstruct point
  2722. "Pointer structure."
  2723. (x :int)
  2724. (y :int))
  2725. CFFI> (with-foreign-object (ptr '(:struct point))
  2726. ;; @lispcmt{Initialize the slots}
  2727. (setf (foreign-slot-value ptr '(:struct point) 'x) 42
  2728. (foreign-slot-value ptr '(:struct point) 'y) 42)
  2729. ;; @lispcmt{Return a list with the coordinates}
  2730. (with-foreign-slots ((x y) ptr (:struct point))
  2731. (list x y)))
  2732. @result{} (42 42)
  2733. @end lisp
  2734. @subheading See Also
  2735. @seealso{defcstruct} @*
  2736. @seealso{foreign-slot-names} @*
  2737. @seealso{foreign-slot-offset} @*
  2738. @seealso{foreign-slot-pointer} @*
  2739. @seealso{with-foreign-slots}
  2740. @c ===================================================================
  2741. @c FOREIGN-TYPE-ALIGNMENT
  2742. @page
  2743. @node foreign-type-alignment, foreign-type-size, foreign-slot-value, Foreign Types
  2744. @heading foreign-type-alignment
  2745. @subheading Syntax
  2746. @c XXX: This is actually a generic function.
  2747. @Function{foreign-type-alignment type @res{} alignment}
  2748. @subheading Arguments and Values
  2749. @table @var
  2750. @item type
  2751. A foreign type.
  2752. @item alignment
  2753. An integer.
  2754. @end table
  2755. @subheading Description
  2756. The function @code{foreign-type-alignment} returns the
  2757. @var{alignment} of @var{type} in bytes.
  2758. @subheading Examples
  2759. @lisp
  2760. CFFI> (foreign-type-alignment :char)
  2761. @result{} 1
  2762. CFFI> (foreign-type-alignment :short)
  2763. @result{} 2
  2764. CFFI> (foreign-type-alignment :int)
  2765. @result{} 4
  2766. @end lisp
  2767. @lisp
  2768. (defcstruct foo
  2769. (a :char))
  2770. CFFI> (foreign-type-alignment '(:struct foo))
  2771. @result{} 1
  2772. @end lisp
  2773. @subheading See Also
  2774. @seealso{foreign-type-size}
  2775. @c ===================================================================
  2776. @c FOREIGN-TYPE-SIZE
  2777. @page
  2778. @node foreign-type-size, free-converted-object, foreign-type-alignment, Foreign Types
  2779. @heading foreign-type-size
  2780. @subheading Syntax
  2781. @c XXX: this is actually a generic function.
  2782. @Function{foreign-type-size type @res{} size}
  2783. @subheading Arguments and Values
  2784. @table @var
  2785. @item type
  2786. A foreign type.
  2787. @item size
  2788. An integer.
  2789. @end table
  2790. @subheading Description
  2791. The function @code{foreign-type-size} return the @var{size} of
  2792. @var{type} in bytes. This includes any padding within and following
  2793. the in-memory representation as needed to create an array of
  2794. @var{type} objects.
  2795. @subheading Examples
  2796. @lisp
  2797. (defcstruct foo
  2798. (a :double)
  2799. (c :char))
  2800. CFFI> (foreign-type-size :double)
  2801. @result{} 8
  2802. CFFI> (foreign-type-size :char)
  2803. @result{} 1
  2804. CFFI> (foreign-type-size '(:struct foo))
  2805. @result{} 16
  2806. @end lisp
  2807. @subheading See Also
  2808. @seealso{foreign-type-alignment}
  2809. @c ===================================================================
  2810. @c FREE-CONVERTED-OBJECT
  2811. @page
  2812. @node free-converted-object, free-translated-object, foreign-type-size, Foreign Types
  2813. @heading free-converted-object
  2814. @subheading Syntax
  2815. @Function{free-converted-object foreign-value type params}
  2816. @subheading Arguments and Values
  2817. @table @var
  2818. @item foreign-value
  2819. The C object to be freed.
  2820. @item type
  2821. A @cffi{} type specifier.
  2822. @item params
  2823. The state returned as the second value from @code{convert-to-foreign};
  2824. used to implement the third argument to @code{free-translated-object}.
  2825. @end table
  2826. @subheading Description
  2827. The return value is unspecified.
  2828. This is an external interface to the type translation facility. In
  2829. the implementation, all foreign functions are ultimately defined as
  2830. type translation wrappers around primitive foreign function
  2831. invocations.
  2832. This function is available mostly for inspection of the type
  2833. translation process, and possibly optimization of special cases of
  2834. your foreign function calls.
  2835. Its behavior is better described under @code{free-translated-object}'s
  2836. documentation.
  2837. @subheading Examples
  2838. @lisp
  2839. CFFI-USER> (convert-to-foreign "a boat" :string)
  2840. @result{} #<FOREIGN-ADDRESS #x097ACDC0>
  2841. @result{} T
  2842. CFFI-USER> (free-converted-object * :string t)
  2843. @result{} NIL
  2844. @end lisp
  2845. @subheading See Also
  2846. @seealso{convert-from-foreign} @*
  2847. @seealso{convert-to-foreign} @*
  2848. @seealso{free-translated-object}
  2849. @c ===================================================================
  2850. @c FREE-TRANSLATED-OBJECT
  2851. @c TODO: update
  2852. @page
  2853. @node free-translated-object, translate-from-foreign, free-converted-object, Foreign Types
  2854. @heading free-translated-object
  2855. @subheading Syntax
  2856. @GenericFunction{free-translated-object value type-name param}
  2857. @subheading Arguments and Values
  2858. @table @var
  2859. @item pointer
  2860. The foreign value returned by @code{translate-to-foreign}.
  2861. @item type-name
  2862. A symbol naming a foreign type defined by @code{defctype}.
  2863. @item param
  2864. The second value, if any, returned by @code{translate-to-foreign}.
  2865. @end table
  2866. @subheading Description
  2867. This generic function may be specialized by user code to perform
  2868. automatic deallocation of foreign objects as they are passed to C
  2869. functions.
  2870. Any methods defined on this generic function must EQL-specialize the
  2871. @var{type-name} parameter on a symbol defined as a foreign type by
  2872. the @code{defctype} macro.
  2873. @subheading See Also
  2874. @seealso{Foreign Type Translators} @*
  2875. @seealso{translate-to-foreign}
  2876. @c ===================================================================
  2877. @c TRANSLATE-FROM-FOREIGN
  2878. @c TODO: update
  2879. @page
  2880. @node translate-from-foreign, translate-to-foreign, free-translated-object, Foreign Types
  2881. @heading translate-from-foreign
  2882. @subheading Syntax
  2883. @GenericFunction{translate-from-foreign foreign-value type-name @
  2884. @res{} lisp-value}
  2885. @subheading Arguments and Values
  2886. @table @var
  2887. @item foreign-value
  2888. The foreign value to convert to a Lisp object.
  2889. @item type-name
  2890. A symbol naming a foreign type defined by @code{defctype}.
  2891. @item lisp-value
  2892. The lisp value to pass in place of @code{foreign-value} to Lisp code.
  2893. @end table
  2894. @subheading Description
  2895. This generic function is invoked by @cffi{} to convert a foreign value to
  2896. a Lisp value, such as when returning from a foreign function, passing
  2897. arguments to a callback function, or accessing a foreign variable.
  2898. To extend the @cffi{} type system by performing custom translations, this
  2899. method may be specialized by @sc{eql}-specializing @code{type-name} on a
  2900. symbol naming a foreign type defined with @code{defctype}. This
  2901. method should return the appropriate Lisp value to use in place of the
  2902. foreign value.
  2903. The results are undefined if the @code{type-name} parameter is
  2904. specialized in any way except an @sc{eql} specializer on a foreign type
  2905. defined with @code{defctype}. Specifically, translations may not be
  2906. defined for built-in types.
  2907. @subheading See Also
  2908. @seealso{Foreign Type Translators} @*
  2909. @seealso{translate-to-foreign} @*
  2910. @seealso{free-translated-object}
  2911. @c ===================================================================
  2912. @c TRANSLATE-TO-FOREIGN
  2913. @c TODO: update
  2914. @page
  2915. @node translate-to-foreign, translate-into-foreign-memory, translate-from-foreign, Foreign Types
  2916. @heading translate-to-foreign
  2917. @subheading Syntax
  2918. @GenericFunction{translate-to-foreign lisp-value type-name @
  2919. @res{} foreign-value, alloc-param}
  2920. @subheading Arguments and Values
  2921. @table @var
  2922. @item lisp-value
  2923. The Lisp value to convert to foreign representation.
  2924. @item type-name
  2925. A symbol naming a foreign type defined by @code{defctype}.
  2926. @item foreign-value
  2927. The foreign value to pass in place of @code{lisp-value} to foreign code.
  2928. @item alloc-param
  2929. If present, this value will be passed to
  2930. @code{free-translated-object}.
  2931. @end table
  2932. @subheading Description
  2933. This generic function is invoked by @cffi{} to convert a Lisp value to a
  2934. foreign value, such as when passing arguments to a foreign function,
  2935. returning a value from a callback, or setting a foreign variable. A
  2936. ``foreign value'' is one appropriate for passing to the next-lowest
  2937. translator, including the low-level translators that are ultimately
  2938. invoked invisibly with @cffi{}.
  2939. To extend the @cffi{} type system by performing custom translations, this
  2940. method may be specialized by @sc{eql}-specializing @code{type-name} on a
  2941. symbol naming a foreign type defined with @code{defctype}. This
  2942. method should return the appropriate foreign value to use in place of
  2943. the Lisp value.
  2944. In cases where @cffi{} can determine the lifetime of the foreign object
  2945. returned by this method, it will invoke @code{free-translated-object}
  2946. on the foreign object at the appropriate time. If
  2947. @code{translate-to-foreign} returns a second value, it will be passed
  2948. as the @code{param} argument to @code{free-translated-object}. This
  2949. can be used to establish communication between the allocation and
  2950. deallocation methods.
  2951. The results are undefined if the @code{type-name} parameter is
  2952. specialized in any way except an @sc{eql} specializer on a foreign type
  2953. defined with @code{defctype}. Specifically, translations may not be
  2954. defined for built-in types.
  2955. @subheading See Also
  2956. @seealso{Foreign Type Translators} @*
  2957. @seealso{translate-from-foreign} @*
  2958. @seealso{free-translated-object}
  2959. @c ===================================================================
  2960. @c TRANSLATE-INTO-FOREIGN-MEMORY
  2961. @page
  2962. @node translate-into-foreign-memory, with-foreign-slots, translate-to-foreign, Foreign Types
  2963. @heading translate-into-foreign-memory
  2964. @subheading Syntax
  2965. @GenericFunction{translate-into-foreign-memory lisp-value type-name pointer}
  2966. @subheading Arguments and Values
  2967. @table @var
  2968. @item lisp-value
  2969. The Lisp value to convert to foreign representation.
  2970. @item type-name
  2971. A symbol or list @code{(:struct @var{structure-name})} naming a foreign type defined by @code{defctype}.
  2972. @item pointer
  2973. The foreign pointer where the translated object should be stored.
  2974. @end table
  2975. @subheading Description
  2976. Translate the Lisp value into the foreign memory location given by
  2977. pointer. The return value is not used.
  2978. @c ===================================================================
  2979. @c WITH-FOREIGN-SLOTS
  2980. @page
  2981. @node with-foreign-slots, , translate-into-foreign-memory, Foreign Types
  2982. @heading with-foreign-slots
  2983. @subheading Syntax
  2984. @Macro{with-foreign-slots (vars ptr type) &body body}
  2985. @subheading Arguments and Values
  2986. @table @var
  2987. @item vars
  2988. A list with each element a symbol, or list of length two with the
  2989. first element @code{:pointer} and the second a symbol.
  2990. @item ptr
  2991. A foreign pointer to a structure.
  2992. @item type
  2993. A structure type.
  2994. @item body
  2995. A list of forms to be executed.
  2996. @end table
  2997. @subheading Description
  2998. The @code{with-foreign-slots} macro creates local symbol macros for each
  2999. var in @var{vars} to reference foreign slots in @var{ptr} of @var{type}.
  3000. If the var is a list starting with @code{:pointer}, it will bind the
  3001. pointer to the slot (rather than the value). It is similar to Common
  3002. Lisp's @code{with-slots} macro.
  3003. @subheading Examples
  3004. @lisp
  3005. (defcstruct tm
  3006. (sec :int)
  3007. (min :int)
  3008. (hour :int)
  3009. (mday :int)
  3010. (mon :int)
  3011. (year :int)
  3012. (wday :int)
  3013. (yday :int)
  3014. (isdst :boolean)
  3015. (zone :string)
  3016. (gmtoff :long))
  3017. CFFI> (with-foreign-object (time :int)
  3018. (setf (mem-ref time :int)
  3019. (foreign-funcall "time" :pointer (null-pointer) :int))
  3020. (foreign-funcall "gmtime" :pointer time (:pointer (:struct tm))))
  3021. @result{} #<A Mac Pointer #x102A30>
  3022. CFFI> (with-foreign-slots ((sec min hour mday mon year) * (:struct tm))
  3023. (format nil "~A:~A:~A, ~A/~A/~A"
  3024. hour min sec (+ 1900 year) mon mday))
  3025. @result{} "7:22:47, 2005/8/2"
  3026. @end lisp
  3027. @subheading See Also
  3028. @seealso{defcstruct} @*
  3029. @seealso{defcunion} @*
  3030. @seealso{foreign-slot-value}
  3031. @c ===================================================================
  3032. @c CHAPTER: Pointers
  3033. @node Pointers, Strings, Foreign Types, Top
  3034. @chapter Pointers
  3035. All C data in @cffi{} is referenced through pointers. This includes
  3036. defined C variables that hold immediate values, and integers.
  3037. To see why this is, consider the case of the C integer. It is not
  3038. only an arbitrary representation for an integer, congruent to Lisp's
  3039. fixnums; the C integer has a specific bit pattern in memory defined by
  3040. the C @acronym{ABI}. Lisp has no such constraint on its fixnums;
  3041. therefore, it only makes sense to think of fixnums as C integers if
  3042. you assume that @cffi{} converts them when necessary, such as when
  3043. storing one for use in a C function call, or as the value of a C
  3044. variable. This requires defining an area of memory@footnote{The
  3045. definition of @dfn{memory} includes the @acronym{CPU} registers.},
  3046. represented through an effective address, and storing it there.
  3047. Due to this compartmentalization, it only makes sense to manipulate
  3048. raw C data in Lisp through pointers to it. For example, while there
  3049. may be a Lisp representation of a @code{struct} that is converted to C
  3050. at store time, you may only manipulate its raw data through a pointer.
  3051. The C compiler does this also, albeit informally.
  3052. @menu
  3053. * Basic Pointer Operations::
  3054. * Allocating Foreign Memory::
  3055. * Accessing Foreign Memory::
  3056. Dictionary
  3057. * foreign-free::
  3058. * foreign-alloc::
  3059. * foreign-symbol-pointer::
  3060. * inc-pointer::
  3061. * incf-pointer::
  3062. * make-pointer::
  3063. * mem-aptr::
  3064. * mem-aref::
  3065. * mem-ref::
  3066. * null-pointer::
  3067. * null-pointer-p::
  3068. * pointerp::
  3069. * pointer-address::
  3070. * pointer-eq::
  3071. * with-foreign-object::
  3072. * with-foreign-objects::
  3073. * with-foreign-pointer::
  3074. @end menu
  3075. @node Basic Pointer Operations, Allocating Foreign Memory, Pointers, Pointers
  3076. @section Basic Pointer Operations
  3077. Manipulating pointers proper can be accomplished through most of the
  3078. other operations defined in the Pointers dictionary, such as
  3079. @code{make-pointer}, @code{pointer-address}, and @code{pointer-eq}.
  3080. When using them, keep in mind that they merely manipulate the Lisp
  3081. representation of pointers, not the values they point to.
  3082. @deftp {Lisp Type} foreign-pointer
  3083. The pointers' representations differ from implementation to
  3084. implementation and have different types. @code{foreign-pointer}
  3085. provides a portable type alias to each of these types.
  3086. @end deftp
  3087. @node Allocating Foreign Memory, Accessing Foreign Memory, Basic Pointer Operations, Pointers
  3088. @section Allocating Foreign Memory
  3089. @cffi{} provides support for stack and heap C memory allocation.
  3090. Stack allocation, done with @code{with-foreign-object}, is sometimes
  3091. called ``dynamic'' allocation in Lisp, because memory allocated as
  3092. such has dynamic extent, much as with @code{let} bindings of special
  3093. variables.
  3094. This should not be confused with what C calls ``dynamic'' allocation,
  3095. or that done with @code{malloc} and friends. This sort of heap
  3096. allocation is done with @code{foreign-alloc}, creating objects that
  3097. exist until freed with @code{foreign-free}.
  3098. @node Accessing Foreign Memory, foreign-free, Allocating Foreign Memory, Pointers
  3099. @section Accessing Foreign Memory
  3100. When manipulating raw C data, consider that all pointers are pointing
  3101. to an array. When you only want one C value, such as a single
  3102. @code{struct}, this array only has one such value. It is worthwhile
  3103. to remember that everything is an array, though, because this is also
  3104. the semantic that C imposes natively.
  3105. C values are accessed as the @code{setf}-able places defined by
  3106. @code{mem-aref} and @code{mem-ref}. Given a pointer and a @cffi{}
  3107. type (@pxref{Foreign Types}), either of these will dereference the
  3108. pointer, translate the C data there back to Lisp, and return the
  3109. result of said translation, performing the reverse operation when
  3110. @code{setf}-ing. To decide which one to use, consider whether you
  3111. would use the array index operator @code{[@var{n}]} or the pointer
  3112. dereference @code{*} in C; use @code{mem-aref} for array indexing and
  3113. @code{mem-ref} for pointer dereferencing.
  3114. @c ===================================================================
  3115. @c FOREIGN-FREE
  3116. @page
  3117. @node foreign-free, foreign-alloc, Accessing Foreign Memory, Pointers
  3118. @heading foreign-free
  3119. @subheading Syntax
  3120. @Function{foreign-free ptr @res{} undefined}
  3121. @subheading Arguments and Values
  3122. @table @var
  3123. @item ptr
  3124. A foreign pointer.
  3125. @end table
  3126. @subheading Description
  3127. The @code{foreign-free} function frees a @code{ptr} previously
  3128. allocated by @code{foreign-alloc}. The consequences of freeing a given
  3129. pointer twice are undefined.
  3130. @subheading Examples
  3131. @lisp
  3132. CFFI> (foreign-alloc :int)
  3133. @result{} #<A Mac Pointer #x1022E0>
  3134. CFFI> (foreign-free *)
  3135. @result{} NIL
  3136. @end lisp
  3137. @subheading See Also
  3138. @seealso{foreign-alloc} @*
  3139. @seealso{with-foreign-pointer}
  3140. @c ===================================================================
  3141. @c FOREIGN-ALLOC
  3142. @page
  3143. @node foreign-alloc, foreign-symbol-pointer, foreign-free, Pointers
  3144. @heading foreign-alloc
  3145. @subheading Syntax
  3146. @Function{foreign-alloc type &key initial-element initial-contents (count 1) @
  3147. null-terminated-p @res{} pointer}
  3148. @subheading Arguments and Values
  3149. @table @var
  3150. @item type
  3151. A foreign type.
  3152. @item initial-element
  3153. A Lisp object.
  3154. @item initial-contents
  3155. A sequence.
  3156. @item count
  3157. An integer. Defaults to 1 or the length of @var{initial-contents} if
  3158. supplied.
  3159. @item null-terminated-p
  3160. A boolean, false by default.
  3161. @item pointer
  3162. A foreign pointer to the newly allocated memory.
  3163. @end table
  3164. @subheading Description
  3165. The @code{foreign-alloc} function allocates enough memory to hold
  3166. @var{count} objects of type @var{type} and returns a
  3167. @var{pointer}. This memory must be explicitly freed using
  3168. @code{foreign-free} once it is no longer needed.
  3169. If @var{initial-element} is supplied, it is used to initialize the
  3170. @var{count} objects the newly allocated memory holds.
  3171. If an @var{initial-contents} sequence is supplied, it must have a
  3172. length less than or equal to @var{count} and each of its elements
  3173. will be used to initialize the contents of the newly allocated
  3174. memory.
  3175. If @var{count} is omitted and @var{initial-contents} is specified, it
  3176. will default to @code{(length @var{initial-contents})}.
  3177. @var{initial-element} and @var{initial-contents} are mutually
  3178. exclusive.
  3179. When @var{null-terminated-p} is true,
  3180. @code{(1+ (max @var{count} (length @var{initial-contents})))} elements
  3181. are allocated and the last one is set to @code{NULL}. Note that in
  3182. this case @var{type} must be a pointer type (ie. a type that
  3183. canonicalizes to @code{:pointer}), otherwise an error is signaled.
  3184. @subheading Examples
  3185. @lisp
  3186. CFFI> (foreign-alloc :char)
  3187. @result{} #<A Mac Pointer #x102D80> ; @lispcmt{A pointer to 1 byte of memory.}
  3188. CFFI> (foreign-alloc :char :count 20)
  3189. @result{} #<A Mac Pointer #x1024A0> ; @lispcmt{A pointer to 20 bytes of memory.}
  3190. CFFI> (foreign-alloc :int :initial-element 12)
  3191. @result{} #<A Mac Pointer #x1028B0>
  3192. CFFI> (mem-ref * :int)
  3193. @result{} 12
  3194. CFFI> (foreign-alloc :int :initial-contents '(1 2 3))
  3195. @result{} #<A Mac Pointer #x102950>
  3196. CFFI> (loop for i from 0 below 3
  3197. collect (mem-aref * :int i))
  3198. @result{} (1 2 3)
  3199. CFFI> (foreign-alloc :int :initial-contents #(1 2 3))
  3200. @result{} #<A Mac Pointer #x102960>
  3201. CFFI> (loop for i from 0 below 3
  3202. collect (mem-aref * :int i))
  3203. @result{} (1 2 3)
  3204. ;;; @lispcmt{Allocate a char** pointer that points to newly allocated memory}
  3205. ;;; @lispcmt{by the :string type translator for the string "foo".}
  3206. CFFI> (foreign-alloc :string :initial-element "foo")
  3207. @result{} #<A Mac Pointer #x102C40>
  3208. @end lisp
  3209. @lisp
  3210. ;;; @lispcmt{Allocate a null-terminated array of strings.}
  3211. ;;; @lispcmt{(Note: FOREIGN-STRING-TO-LISP returns NIL when passed a null pointer)}
  3212. CFFI> (foreign-alloc :string
  3213. :initial-contents '("foo" "bar" "baz")
  3214. :null-terminated-p t)
  3215. @result{} #<A Mac Pointer #x102D20>
  3216. CFFI> (loop for i from 0 below 4
  3217. collect (mem-aref * :string i))
  3218. @result{} ("foo" "bar" "baz" NIL)
  3219. CFFI> (progn
  3220. (dotimes (i 3)
  3221. (foreign-free (mem-aref ** :pointer i)))
  3222. (foreign-free **))
  3223. @result{} nil
  3224. @end lisp
  3225. @subheading See Also
  3226. @seealso{foreign-free} @*
  3227. @seealso{with-foreign-object} @*
  3228. @seealso{with-foreign-pointer}
  3229. @c ===================================================================
  3230. @c FOREIGN-SYMBOL-POINTER
  3231. @page
  3232. @node foreign-symbol-pointer, inc-pointer, foreign-alloc, Pointers
  3233. @heading foreign-symbol-pointer
  3234. @subheading Syntax
  3235. @Function{foreign-symbol-pointer foreign-name &key library @res{} pointer}
  3236. @subheading Arguments and Values
  3237. @table @var
  3238. @item foreign-name
  3239. A string.
  3240. @item pointer
  3241. A foreign pointer, or @code{nil}.
  3242. @item library
  3243. A Lisp symbol or an instance of @code{foreign-library}.
  3244. @end table
  3245. @subheading Description
  3246. The function @code{foreign-symbol-pointer} will return a foreign
  3247. pointer corresponding to the foreign symbol denoted by the string
  3248. @var{foreign-name}. If a foreign symbol named @var{foreign-name}
  3249. doesn't exist, @code{nil} is returned.
  3250. ABI name manglings will be performed on @var{foreign-name} by
  3251. @code{foreign-symbol-pointer} if necessary. (eg: adding a leading
  3252. underscore on darwin/ppc)
  3253. @var{library} should name a foreign library as defined by
  3254. @code{define-foreign-library}, @code{:default} (which is the default)
  3255. or an instance of @code{foreign-library} as returned by
  3256. @code{load-foreign-library}.
  3257. @strong{Important note:} do not keep these pointers across saved Lisp
  3258. cores as the foreign-library may move across sessions.
  3259. @subheading Examples
  3260. @lisp
  3261. CFFI> (foreign-symbol-pointer "errno")
  3262. @result{} #<A Mac Pointer #xA0008130>
  3263. CFFI> (foreign-symbol-pointer "strerror")
  3264. @result{} #<A Mac Pointer #x9002D0F8>
  3265. CFFI> (foreign-funcall-pointer * () :int (mem-ref ** :int) :string)
  3266. @result{} "No such file or directory"
  3267. CFFI> (foreign-symbol-pointer "inexistent symbol")
  3268. @result{} NIL
  3269. @end lisp
  3270. @subheading See Also
  3271. @seealso{defcvar}
  3272. @c ===================================================================
  3273. @c INC-POINTER
  3274. @page
  3275. @node inc-pointer, incf-pointer, foreign-symbol-pointer, Pointers
  3276. @heading inc-pointer
  3277. @subheading Syntax
  3278. @Function{inc-pointer pointer offset @res{} new-pointer}
  3279. @subheading Arguments and Values
  3280. @table @var
  3281. @item pointer
  3282. @itemx new-pointer
  3283. A foreign pointer.
  3284. @item offset
  3285. An integer.
  3286. @end table
  3287. @subheading Description
  3288. The function @code{inc-pointer} will return a @var{new-pointer} pointing
  3289. @var{offset} bytes past @var{pointer}.
  3290. @subheading Examples
  3291. @lisp
  3292. CFFI> (foreign-string-alloc "Common Lisp")
  3293. @result{} #<A Mac Pointer #x102EA0>
  3294. CFFI> (inc-pointer * 7)
  3295. @result{} #<A Mac Pointer #x102EA7>
  3296. CFFI> (foreign-string-to-lisp *)
  3297. @result{} "Lisp"
  3298. @end lisp
  3299. @subheading See Also
  3300. @seealso{incf-pointer} @*
  3301. @seealso{make-pointer} @*
  3302. @seealso{pointerp} @*
  3303. @seealso{null-pointer} @*
  3304. @seealso{null-pointer-p}
  3305. @c ===================================================================
  3306. @c INCF-POINTER
  3307. @page
  3308. @node incf-pointer, make-pointer, inc-pointer, Pointers
  3309. @heading incf-pointer
  3310. @subheading Syntax
  3311. @Macro{incf-pointer place &optional (offset 1) @res{} new-pointer}
  3312. @subheading Arguments and Values
  3313. @table @var
  3314. @item place
  3315. A @code{setf} place.
  3316. @item new-pointer
  3317. A foreign pointer.
  3318. @item offset
  3319. An integer.
  3320. @end table
  3321. @subheading Description
  3322. The @code{incf-pointer} macro takes the foreign pointer from
  3323. @var{place} and creates a @var{new-pointer} incremented by
  3324. @var{offset} bytes and which is stored in @var{place}.
  3325. @subheading Examples
  3326. @lisp
  3327. CFFI> (defparameter *two-words* (foreign-string-alloc "Common Lisp"))
  3328. @result{} *TWO-WORDS*
  3329. CFFI> (defparameter *one-word* *two-words*)
  3330. @result{} *ONE-WORD*
  3331. CFFI> (incf-pointer *one-word* 7)
  3332. @result{} #.(SB-SYS:INT-SAP #X00600457)
  3333. CFFI> (foreign-string-to-lisp *one-word*)
  3334. @result{} "Lisp"
  3335. CFFI> (foreign-string-to-lisp *two-words*)
  3336. @result{} "Common Lisp"
  3337. @end lisp
  3338. @subheading See Also
  3339. @seealso{inc-pointer} @*
  3340. @seealso{make-pointer} @*
  3341. @seealso{pointerp} @*
  3342. @seealso{null-pointer} @*
  3343. @seealso{null-pointer-p}
  3344. @c ===================================================================
  3345. @c MAKE-POINTER
  3346. @page
  3347. @node make-pointer, mem-aptr, incf-pointer, Pointers
  3348. @heading make-pointer
  3349. @subheading Syntax
  3350. @Function{make-pointer address @res{} ptr}
  3351. @subheading Arguments and Values
  3352. @table @var
  3353. @item address
  3354. An integer.
  3355. @item ptr
  3356. A foreign pointer.
  3357. @end table
  3358. @subheading Description
  3359. The function @code{make-pointer} will return a foreign pointer
  3360. pointing to @var{address}.
  3361. @subheading Examples
  3362. @lisp
  3363. CFFI> (make-pointer 42)
  3364. @result{} #<FOREIGN-ADDRESS #x0000002A>
  3365. CFFI> (pointerp *)
  3366. @result{} T
  3367. CFFI> (pointer-address **)
  3368. @result{} 42
  3369. CFFI> (inc-pointer *** -42)
  3370. @result{} #<FOREIGN-ADDRESS #x00000000>
  3371. CFFI> (null-pointer-p *)
  3372. @result{} T
  3373. CFFI> (typep ** 'foreign-pointer)
  3374. @result{} T
  3375. @end lisp
  3376. @subheading See Also
  3377. @seealso{inc-pointer} @*
  3378. @seealso{null-pointer} @*
  3379. @seealso{null-pointer-p} @*
  3380. @seealso{pointerp} @*
  3381. @seealso{pointer-address} @*
  3382. @seealso{pointer-eq} @*
  3383. @seealso{mem-ref}
  3384. @c ===================================================================
  3385. @c MEM-APTR
  3386. @page
  3387. @node mem-aptr, mem-aref, make-pointer, Pointers
  3388. @heading mem-aptr
  3389. @subheading Syntax
  3390. @Accessor{mem-aptr ptr type &optional (index 0)}
  3391. @subheading Arguments and Values
  3392. @table @var
  3393. @item ptr
  3394. A foreign pointer.
  3395. @item type
  3396. A foreign type.
  3397. @item index
  3398. An integer.
  3399. @item new-value
  3400. A Lisp value compatible with @var{type}.
  3401. @end table
  3402. @subheading Description
  3403. The @code{mem-aptr} function finds the pointer to an element of the array.
  3404. @lisp
  3405. (mem-aptr ptr type n)
  3406. ;; @lispcmt{is identical to:}
  3407. (inc-pointer ptr (* n (foreign-type-size type)))
  3408. @end lisp
  3409. @subheading Examples
  3410. @lisp
  3411. CFFI> (with-foreign-string (str "Hello, foreign world!")
  3412. (mem-aptr str :char 6))
  3413. @result{} #.(SB-SYS:INT-SAP #X0063D4B6)
  3414. @end lisp
  3415. @c ===================================================================
  3416. @c MEM-AREF
  3417. @page
  3418. @node mem-aref, mem-ref, mem-aptr, Pointers
  3419. @heading mem-aref
  3420. @subheading Syntax
  3421. @Accessor{mem-aref ptr type &optional (index 0)}
  3422. (setf (@strong{mem-aref} @emph{ptr type &optional (index 0)) new-value})
  3423. @subheading Arguments and Values
  3424. @table @var
  3425. @item ptr
  3426. A foreign pointer.
  3427. @item type
  3428. A foreign type.
  3429. @item index
  3430. An integer.
  3431. @item new-value
  3432. A Lisp value compatible with @var{type}.
  3433. @end table
  3434. @subheading Description
  3435. The @code{mem-aref} function is similar to @code{mem-ref} but will
  3436. automatically calculate the offset from an @var{index}.
  3437. @lisp
  3438. (mem-aref ptr type n)
  3439. ;; @lispcmt{is identical to:}
  3440. (mem-ref ptr type (* n (foreign-type-size type)))
  3441. @end lisp
  3442. @subheading Examples
  3443. @lisp
  3444. CFFI> (with-foreign-string (str "Hello, foreign world!")
  3445. (mem-aref str :char 6))
  3446. @result{} 32
  3447. CFFI> (code-char *)
  3448. @result{} #\Space
  3449. CFFI> (with-foreign-object (array :int 10)
  3450. (loop for i below 10
  3451. do (setf (mem-aref array :int i) (random 100)))
  3452. (loop for i below 10 collect (mem-aref array :int i)))
  3453. @result{} (22 7 22 52 69 1 46 93 90 65)
  3454. @end lisp
  3455. @subheading Compatibility Note
  3456. For compatibility with older versions of CFFI, @ref{mem-aref} will
  3457. produce a pointer for the deprecated bare structure specification, but
  3458. it is consistent with other types for the current specification form
  3459. @code{(:struct @var{structure-name})} and provides a Lisp object
  3460. translated from the structure (by default a plist). In order to obtain
  3461. the pointer, you should use the new function @ref{mem-aptr}.
  3462. @subheading See Also
  3463. @seealso{mem-ref} @*
  3464. @seealso{mem-aptr}
  3465. @c ===================================================================
  3466. @c MEM-REF
  3467. @page
  3468. @node mem-ref, null-pointer, mem-aref, Pointers
  3469. @heading mem-ref
  3470. @subheading Syntax
  3471. @Accessor{mem-ref ptr type &optional offset @res{} object}
  3472. @subheading Arguments and Values
  3473. @table @var
  3474. @item ptr
  3475. A pointer.
  3476. @item type
  3477. A foreign type.
  3478. @item offset
  3479. An integer (in byte units).
  3480. @item object
  3481. The value @var{ptr} points to.
  3482. @end table
  3483. @subheading Description
  3484. @subheading Examples
  3485. @lisp
  3486. CFFI> (with-foreign-string (ptr "Saluton")
  3487. (setf (mem-ref ptr :char 3) (char-code #\a))
  3488. (loop for i from 0 below 8
  3489. collect (code-char (mem-ref ptr :char i))))
  3490. @result{} (#\S #\a #\l #\a #\t #\o #\n #\Null)
  3491. CFFI> (setq ptr-to-int (foreign-alloc :int))
  3492. @result{} #<A Mac Pointer #x1047D0>
  3493. CFFI> (mem-ref ptr-to-int :int)
  3494. @result{} 1054619
  3495. CFFI> (setf (mem-ref ptr-to-int :int) 1984)
  3496. @result{} 1984
  3497. CFFI> (mem-ref ptr-to-int :int)
  3498. @result{} 1984
  3499. @end lisp
  3500. @subheading See Also
  3501. @seealso{mem-aref}
  3502. @c ===================================================================
  3503. @c NULL-POINTER
  3504. @page
  3505. @node null-pointer, null-pointer-p, mem-ref, Pointers
  3506. @heading null-pointer
  3507. @subheading Syntax
  3508. @Function{null-pointer @res{} pointer}
  3509. @subheading Arguments and Values
  3510. @table @var
  3511. @item pointer
  3512. A @code{NULL} pointer.
  3513. @end table
  3514. @subheading Description
  3515. The function @code{null-pointer} returns a null pointer.
  3516. @subheading Examples
  3517. @lisp
  3518. CFFI> (null-pointer)
  3519. @result{} #<A Null Mac Pointer>
  3520. CFFI> (pointerp *)
  3521. @result{} T
  3522. @end lisp
  3523. @subheading See Also
  3524. @seealso{null-pointer-p} @*
  3525. @seealso{make-pointer}
  3526. @c ===================================================================
  3527. @c NULL-POINTER-P
  3528. @page
  3529. @node null-pointer-p, pointerp, null-pointer, Pointers
  3530. @heading null-pointer-p
  3531. @subheading Syntax
  3532. @Function{null-pointer-p ptr @res{} boolean}
  3533. @subheading Arguments and Values
  3534. @table @var
  3535. @item ptr
  3536. A foreign pointer that may be a null pointer.
  3537. @item boolean
  3538. @code{T} or @code{NIL}.
  3539. @end table
  3540. @subheading Description
  3541. The function @code{null-pointer-p} returns true if @var{ptr} is a null
  3542. pointer and false otherwise.
  3543. @subheading Examples
  3544. @lisp
  3545. CFFI> (null-pointer-p (null-pointer))
  3546. @result{} T
  3547. @end lisp
  3548. @lisp
  3549. (defun contains-str-p (big little)
  3550. (not (null-pointer-p
  3551. (foreign-funcall "strstr" :string big :string little :pointer))))
  3552. CFFI> (contains-str-p "Popcorns" "corn")
  3553. @result{} T
  3554. CFFI> (contains-str-p "Popcorns" "salt")
  3555. @result{} NIL
  3556. @end lisp
  3557. @subheading See Also
  3558. @seealso{null-pointer} @*
  3559. @seealso{pointerp}
  3560. @c ===================================================================
  3561. @c POINTERP
  3562. @page
  3563. @node pointerp, pointer-address, null-pointer-p, Pointers
  3564. @heading pointerp
  3565. @subheading Syntax
  3566. @Function{pointerp ptr @res{} boolean}
  3567. @subheading Arguments and Values
  3568. @table @var
  3569. @item ptr
  3570. An object that may be a foreign pointer.
  3571. @item boolean
  3572. @code{T} or @code{NIL}.
  3573. @end table
  3574. @subheading Description
  3575. The function @code{pointerp} returns true if @var{ptr} is a foreign
  3576. pointer and false otherwise.
  3577. @subheading Implementation-specific Notes
  3578. In Allegro CL, foreign pointers are integers thus in this
  3579. implementation @code{pointerp} will return true for any ordinary integer.
  3580. @subheading Examples
  3581. @lisp
  3582. CFFI> (foreign-alloc 32)
  3583. @result{} #<A Mac Pointer #x102D20>
  3584. CFFI> (pointerp *)
  3585. @result{} T
  3586. CFFI> (pointerp "this is not a pointer")
  3587. @result{} NIL
  3588. @end lisp
  3589. @subheading See Also
  3590. @seealso{make-pointer}
  3591. @seealso{null-pointer-p}
  3592. @c ===================================================================
  3593. @c POINTER-ADDRESS
  3594. @page
  3595. @node pointer-address, pointer-eq, pointerp, Pointers
  3596. @heading pointer-address
  3597. @subheading Syntax
  3598. @Function{pointer-address ptr @res{} address}
  3599. @subheading Arguments and Values
  3600. @table @var
  3601. @item ptr
  3602. A foreign pointer.
  3603. @item address
  3604. An integer.
  3605. @end table
  3606. @subheading Description
  3607. The function @code{pointer-address} will return the @var{address} of
  3608. a foreign pointer @var{ptr}.
  3609. @subheading Examples
  3610. @lisp
  3611. CFFI> (pointer-address (null-pointer))
  3612. @result{} 0
  3613. CFFI> (pointer-address (make-pointer 123))
  3614. @result{} 123
  3615. @end lisp
  3616. @subheading See Also
  3617. @seealso{make-pointer} @*
  3618. @seealso{inc-pointer} @*
  3619. @seealso{null-pointer} @*
  3620. @seealso{null-pointer-p} @*
  3621. @seealso{pointerp} @*
  3622. @seealso{pointer-eq} @*
  3623. @seealso{mem-ref}
  3624. @c ===================================================================
  3625. @c POINTER-EQ
  3626. @page
  3627. @node pointer-eq, with-foreign-object, pointer-address, Pointers
  3628. @heading pointer-eq
  3629. @subheading Syntax
  3630. @Function{pointer-eq ptr1 ptr2 @res{} boolean}
  3631. @subheading Arguments and Values
  3632. @table @var
  3633. @item ptr1
  3634. @itemx ptr2
  3635. A foreign pointer.
  3636. @item boolean
  3637. @code{T} or @code{NIL}.
  3638. @end table
  3639. @subheading Description
  3640. The function @code{pointer-eq} returns true if @var{ptr1} and
  3641. @var{ptr2} point to the same memory address and false otherwise.
  3642. @subheading Implementation-specific Notes
  3643. The representation of foreign pointers varies across the various Lisp
  3644. implementations as does the behaviour of the built-in Common Lisp
  3645. equality predicates. Comparing two pointers that point to the same
  3646. address with @code{EQ} Lisps will return true on some Lisps, others require
  3647. more general predicates like @code{EQL} or @code{EQUALP} and finally
  3648. some will return false using any of these predicates. Therefore, for
  3649. portability, you should use @code{POINTER-EQ}.
  3650. @subheading Examples
  3651. This is an example using @acronym{SBCL}, see the
  3652. implementation-specific notes above.
  3653. @lisp
  3654. CFFI> (eql (null-pointer) (null-pointer))
  3655. @result{} NIL
  3656. CFFI> (pointer-eq (null-pointer) (null-pointer))
  3657. @result{} T
  3658. @end lisp
  3659. @subheading See Also
  3660. @seealso{inc-pointer}
  3661. @c ===================================================================
  3662. @c WITH-FOREIGN-OBJECT
  3663. @page
  3664. @node with-foreign-object, with-foreign-pointer, pointer-eq, Pointers
  3665. @heading with-foreign-object, with-foreign-objects
  3666. @subheading Syntax
  3667. @Macro{with-foreign-object (var type &optional count) &body body}
  3668. @anchor{with-foreign-objects}
  3669. @Macro{with-foreign-objects (bindings) &body body}
  3670. bindings ::= @{(var type &optional count)@}* @*
  3671. @subheading Arguments and Values
  3672. @table @var
  3673. @item var
  3674. A symbol.
  3675. @item type
  3676. A foreign type, evaluated.
  3677. @item count
  3678. An integer.
  3679. @end table
  3680. @subheading Description
  3681. The macros @code{with-foreign-object} and @code{with-foreign-objects}
  3682. bind @var{var} to a pointer to @var{count} newly allocated objects
  3683. of type @var{type} during @var{body}. The buffer has dynamic extent
  3684. and may be stack allocated if supported by the host Lisp.
  3685. @subheading Examples
  3686. @lisp
  3687. CFFI> (with-foreign-object (array :int 10)
  3688. (dotimes (i 10)
  3689. (setf (mem-aref array :int i) (random 100)))
  3690. (loop for i below 10
  3691. collect (mem-aref array :int i)))
  3692. @result{} (22 7 22 52 69 1 46 93 90 65)
  3693. @end lisp
  3694. @subheading See Also
  3695. @seealso{foreign-alloc}
  3696. @c ===================================================================
  3697. @c WITH-FOREIGN-POINTER
  3698. @page
  3699. @node with-foreign-pointer, , with-foreign-object, Pointers
  3700. @heading with-foreign-pointer
  3701. @subheading Syntax
  3702. @Macro{with-foreign-pointer (var size &optional size-var) &body body}
  3703. @subheading Arguments and Values
  3704. @table @var
  3705. @item var
  3706. @itemx size-var
  3707. A symbol.
  3708. @item size
  3709. An integer.
  3710. @item body
  3711. A list of forms to be executed.
  3712. @end table
  3713. @subheading Description
  3714. The @code{with-foreign-pointer} macro, binds @var{var} to @var{size}
  3715. bytes of foreign memory during @var{body}. The pointer in @var{var}
  3716. is invalid beyond the dynamic extend of @var{body} and may be
  3717. stack-allocated if supported by the implementation.
  3718. If @var{size-var} is supplied, it will be bound to @var{size} during
  3719. @var{body}.
  3720. @subheading Examples
  3721. @lisp
  3722. CFFI> (with-foreign-pointer (string 4 size)
  3723. (setf (mem-ref string :char (1- size)) 0)
  3724. (lisp-string-to-foreign "Popcorns" string size)
  3725. (loop for i from 0 below size
  3726. collect (code-char (mem-ref string :char i))))
  3727. @result{} (#\P #\o #\p #\Null)
  3728. @end lisp
  3729. @subheading See Also
  3730. @seealso{foreign-alloc} @*
  3731. @seealso{foreign-free}
  3732. @c ===================================================================
  3733. @c CHAPTER: Strings
  3734. @node Strings, Variables, Pointers, Top
  3735. @chapter Strings
  3736. As with many languages, Lisp and C have special support for logical
  3737. arrays of characters, going so far as to give them a special name,
  3738. ``strings''. In that spirit, @cffi{} provides special support for
  3739. translating between Lisp and C strings.
  3740. The @code{:string} type and the symbols related below also serve as an
  3741. example of what you can do portably with @cffi{}; were it not
  3742. included, you could write an equally functional @file{strings.lisp}
  3743. without referring to any implementation-specific symbols.
  3744. @menu
  3745. Dictionary
  3746. * *default-foreign-encoding*::
  3747. * foreign-string-alloc::
  3748. * foreign-string-free::
  3749. * foreign-string-to-lisp::
  3750. * lisp-string-to-foreign::
  3751. * with-foreign-string::
  3752. * with-foreign-strings::
  3753. * with-foreign-pointer-as-string::
  3754. @end menu
  3755. @c ===================================================================
  3756. @c *DEFAULT-FOREIGN-ENCODING*
  3757. @page
  3758. @node *default-foreign-encoding*, foreign-string-alloc, Strings, Strings
  3759. @heading *default-foreign-encoding*
  3760. @subheading Syntax
  3761. @Variable{*default-foreign-encoding*}
  3762. @subheading Value type
  3763. A keyword.
  3764. @subheading Initial value
  3765. @code{:utf-8}
  3766. @subheading Description
  3767. This special variable holds the default foreign encoding.
  3768. @subheading Examples
  3769. @lisp
  3770. CFFI> *default-foreign-encoding*
  3771. :utf-8
  3772. CFFI> (foreign-funcall "strdup" (:string :encoding :utf-16) "foo" :string)
  3773. "f"
  3774. CFFI> (let ((*default-foreign-encoding* :utf-16))
  3775. (foreign-funcall "strdup" (:string :encoding :utf-16) "foo" :string))
  3776. "foo"
  3777. @end lisp
  3778. @subheading See also
  3779. @seealso{Other Types} (@code{:string} type) @*
  3780. @seealso{foreign-string-alloc} @*
  3781. @seealso{foreign-string-to-lisp} @*
  3782. @seealso{lisp-string-to-foreign} @*
  3783. @seealso{with-foreign-string} @*
  3784. @seealso{with-foreign-pointer-as-string}
  3785. @c ===================================================================
  3786. @c FOREIGN-STRING-ALLOC
  3787. @page
  3788. @node foreign-string-alloc, foreign-string-free, *default-foreign-encoding*, Strings
  3789. @heading foreign-string-alloc
  3790. @subheading Syntax
  3791. @Function{foreign-string-alloc string &key encoding null-terminated-p @
  3792. start end @res{} pointer}
  3793. @subheading Arguments and Values
  3794. @table @emph
  3795. @item @var{string}
  3796. A Lisp string.
  3797. @item @var{encoding}
  3798. Foreign encoding. Defaults to @code{*default-foreign-encoding*}.
  3799. @item @var{null-terminated-p}
  3800. Boolean, defaults to true.
  3801. @item @var{start}, @var{end}
  3802. Bounding index designators of @var{string}. 0 and @code{nil}, by
  3803. default.
  3804. @item @var{pointer}
  3805. A pointer to the newly allocated foreign string.
  3806. @end table
  3807. @subheading Description
  3808. The @code{foreign-string-alloc} function allocates foreign memory
  3809. holding a copy of @var{string} converted using the specified
  3810. @var{encoding}. @var{Start} specifies an offset into @var{string} and
  3811. @var{end} marks the position following the last element of the foreign
  3812. string.
  3813. This string must be freed with @code{foreign-string-free}.
  3814. If @var{null-terminated-p} is false, the string will not be
  3815. null-terminated.
  3816. @subheading Examples
  3817. @lisp
  3818. CFFI> (defparameter *str* (foreign-string-alloc "Hello, foreign world!"))
  3819. @result{} #<FOREIGN-ADDRESS #x00400560>
  3820. CFFI> (foreign-funcall "strlen" :pointer *str* :int)
  3821. @result{} 21
  3822. @end lisp
  3823. @subheading See Also
  3824. @seealso{foreign-string-free} @*
  3825. @seealso{with-foreign-string}
  3826. @c @seealso{:string}
  3827. @c ===================================================================
  3828. @c FOREIGN-STRING-FREE
  3829. @page
  3830. @node foreign-string-free, foreign-string-to-lisp, foreign-string-alloc, Strings
  3831. @heading foreign-string-free
  3832. @subheading Syntax
  3833. @Function{foreign-string-free pointer}
  3834. @subheading Arguments and Values
  3835. @table @var
  3836. @item pointer
  3837. A pointer to a string allocated by @code{foreign-string-alloc}.
  3838. @end table
  3839. @subheading Description
  3840. The @code{foreign-string-free} function frees a foreign string
  3841. allocated by @code{foreign-string-alloc}.
  3842. @subheading Examples
  3843. @subheading See Also
  3844. @seealso{foreign-string-alloc}
  3845. @c ===================================================================
  3846. @c FOREIGN-STRING-TO-LISP
  3847. @page
  3848. @node foreign-string-to-lisp, lisp-string-to-foreign, foreign-string-free, Strings
  3849. @heading foreign-string-to-lisp
  3850. @subheading Syntax
  3851. @Function{foreign-string-to-lisp ptr &key offset count max-chars @
  3852. encoding @res{} string}
  3853. @subheading Arguments and Values
  3854. @table @var
  3855. @item ptr
  3856. A pointer.
  3857. @item offset
  3858. An integer greater than or equal to 0. Defauls to 0.
  3859. @item count
  3860. Either @code{nil} (the default), or an integer greater than or equal to 0.
  3861. @item max-chars
  3862. An integer greater than or equal to 0.
  3863. @code{(1- array-total-size-limit)}, by default.
  3864. @item encoding
  3865. Foreign encoding. Defaults to @code{*default-foreign-encoding*}.
  3866. @item string
  3867. A Lisp string.
  3868. @end table
  3869. @subheading Description
  3870. The @code{foreign-string-to-lisp} function converts at most
  3871. @var{count} octets from @var{ptr} into a Lisp string, using the
  3872. defined @var{encoding}.
  3873. If @var{count} is @code{nil} (the default), characters are copied
  3874. until @var{max-chars} is reached or a @code{NULL} character is found.
  3875. If @var{ptr} is a null pointer, returns @code{nil}.
  3876. Note that the @code{:string} type will automatically convert between
  3877. Lisp strings and foreign strings.
  3878. @subheading Examples
  3879. @lisp
  3880. CFFI> (foreign-funcall "getenv" :string "HOME" :pointer)
  3881. @result{} #<FOREIGN-ADDRESS #xBFFFFFD5>
  3882. CFFI> (foreign-string-to-lisp *)
  3883. @result{} "/Users/luis"
  3884. @end lisp
  3885. @subheading See Also
  3886. @seealso{lisp-string-to-foreign} @*
  3887. @seealso{foreign-string-alloc}
  3888. @c @seealso{:string}
  3889. @c ===================================================================
  3890. @c LISP-STRING-TO-FOREIGN
  3891. @page
  3892. @node lisp-string-to-foreign, with-foreign-string, foreign-string-to-lisp, Strings
  3893. @heading lisp-string-to-foreign
  3894. @subheading Syntax
  3895. @Function{lisp-string-to-foreign string buffer bufsize &key start @
  3896. end offset encoding @res{} buffer}
  3897. @subheading Arguments and Values
  3898. @table @emph
  3899. @item @var{string}
  3900. A Lisp string.
  3901. @item @var{buffer}
  3902. A foreign pointer.
  3903. @item @var{bufsize}
  3904. An integer.
  3905. @item @var{start}, @var{end}
  3906. Bounding index designators of @var{string}. 0 and @code{nil}, by
  3907. default.
  3908. @item @var{offset}
  3909. An integer greater than or equal to 0. Defauls to 0.
  3910. @item @var{encoding}
  3911. Foreign encoding. Defaults to @code{*default-foreign-encoding*}.
  3912. @end table
  3913. @subheading Description
  3914. The @code{lisp-string-to-foreign} function copies at most
  3915. @var{bufsize}-1 octets from a Lisp @var{string} using the specified
  3916. @var{encoding} into @var{buffer}+@var{offset}. The foreign string will
  3917. be null-terminated.
  3918. @var{Start} specifies an offset into @var{string} and
  3919. @var{end} marks the position following the last element of the foreign
  3920. string.
  3921. @subheading Examples
  3922. @lisp
  3923. CFFI> (with-foreign-pointer-as-string (str 255)
  3924. (lisp-string-to-foreign "Hello, foreign world!" str 6))
  3925. @result{} "Hello"
  3926. @end lisp
  3927. @subheading See Also
  3928. @seealso{foreign-string-alloc} @*
  3929. @seealso{foreign-string-to-lisp} @*
  3930. @seealso{with-foreign-pointer-as-string}
  3931. @c ===================================================================
  3932. @c WITH-FOREIGN-STRING
  3933. @page
  3934. @node with-foreign-string, with-foreign-pointer-as-string, lisp-string-to-foreign, Strings
  3935. @heading with-foreign-string, with-foreign-strings
  3936. @subheading Syntax
  3937. @Macro{with-foreign-string (var-or-vars string &rest args) &body body}
  3938. @anchor{with-foreign-strings}
  3939. @Macro{with-foreign-strings (bindings) &body body}
  3940. var-or-vars ::= var | (var &optional octet-size-var) @*
  3941. bindings ::= @{(var-or-vars string &rest args)@}*
  3942. @subheading Arguments and Values
  3943. @table @emph
  3944. @item @var{var}, @var{byte-size-var}
  3945. A symbol.
  3946. @item @var{string}
  3947. A Lisp string.
  3948. @item @var{body}
  3949. A list of forms to be executed.
  3950. @end table
  3951. @subheading Description
  3952. The @code{with-foreign-string} macro will bind @var{var} to a newly
  3953. allocated foreign string containing @var{string}. @var{Args} is passed
  3954. to the underlying @code{foreign-string-alloc} call.
  3955. If @var{octet-size-var} is provided, it will be bound the length of
  3956. foreign string in octets including the null terminator.
  3957. @subheading Examples
  3958. @lisp
  3959. CFFI> (with-foreign-string (foo "12345")
  3960. (foreign-funcall "strlen" :pointer foo :int))
  3961. @result{} 5
  3962. @end lisp
  3963. @subheading See Also
  3964. @seealso{foreign-string-alloc} @*
  3965. @seealso{with-foreign-pointer-as-string}
  3966. @c ===================================================================
  3967. @c WITH-FOREIGN-POINTER-AS-STRING
  3968. @page
  3969. @node with-foreign-pointer-as-string, , with-foreign-string, Strings
  3970. @heading with-foreign-pointer-as-string
  3971. @subheading Syntax
  3972. @Macro{with-foreign-pointer-as-string (var size &optional size-var @
  3973. &rest args) &body body @res{} string}
  3974. @subheading Arguments and Values
  3975. @table @var
  3976. @item var
  3977. A symbol.
  3978. @item string
  3979. A Lisp string.
  3980. @item body
  3981. List of forms to be executed.
  3982. @end table
  3983. @subheading Description
  3984. The @code{with-foreign-pointer-as-string} macro is similar to
  3985. @code{with-foreign-pointer} except that @var{var} is used as the
  3986. returned value of an implicit @code{progn} around @var{body}, after
  3987. being converted to a Lisp string using the provided @var{args}.
  3988. @subheading Examples
  3989. @lisp
  3990. CFFI> (with-foreign-pointer-as-string (str 6 str-size :encoding :ascii)
  3991. (lisp-string-to-foreign "Hello, foreign world!" str str-size))
  3992. @result{} "Hello"
  3993. @end lisp
  3994. @subheading See Also
  3995. @seealso{foreign-string-alloc} @*
  3996. @seealso{with-foreign-string}
  3997. @c ===================================================================
  3998. @c CHAPTER: Variables
  3999. @node Variables, Functions, Strings, Top
  4000. @chapter Variables
  4001. @menu
  4002. Dictionary
  4003. * defcvar::
  4004. * get-var-pointer::
  4005. @end menu
  4006. @c ===================================================================
  4007. @c DEFCVAR
  4008. @page
  4009. @node defcvar, get-var-pointer, Variables, Variables
  4010. @heading defcvar
  4011. @subheading Syntax
  4012. @Macro{defcvar name-and-options type &optional documentation @res{} lisp-name}
  4013. @var{name-and-options} ::= name | (name &key read-only (library :default)) @*
  4014. @var{name} ::= lisp-name [foreign-name] | foreign-name [lisp-name] @*
  4015. @subheading Arguments and Values
  4016. @table @var
  4017. @item foreign-name
  4018. A string denoting a foreign function.
  4019. @item lisp-name
  4020. A symbol naming the Lisp function to be created.
  4021. @item type
  4022. A foreign type.
  4023. @item read-only
  4024. A boolean.
  4025. @item documentation
  4026. A Lisp string; not evaluated.
  4027. @end table
  4028. @subheading Description
  4029. The @code{defcvar} macro defines a symbol macro @var{lisp-name} that looks
  4030. up @var{foreign-name} and dereferences it acording to @var{type}. It
  4031. can also be @code{setf}ed, unless @var{read-only} is true, in which
  4032. case an error will be signaled.
  4033. When one of @var{lisp-name} or @var{foreign-name} is omitted, the
  4034. other is automatically derived using the following rules:
  4035. @itemize
  4036. @item
  4037. Foreign names are converted to Lisp names by uppercasing, replacing
  4038. underscores with hyphens, and wrapping around asterisks.
  4039. @item
  4040. Lisp names are converted to foreign names by lowercasing, replacing
  4041. hyphens with underscores, and removing asterisks, if any.
  4042. @end itemize
  4043. @subheading Examples
  4044. @lisp
  4045. CFFI> (defcvar "errno" :int)
  4046. @result{} *ERRNO*
  4047. CFFI> (foreign-funcall "strerror" :int *errno* :string)
  4048. @result{} "Inappropriate ioctl for device"
  4049. CFFI> (setf *errno* 1)
  4050. @result{} 1
  4051. CFFI> (foreign-funcall "strerror" :int *errno* :string)
  4052. @result{} "Operation not permitted"
  4053. @end lisp
  4054. Trying to modify a read-only foreign variable:
  4055. @lisp
  4056. CFFI> (defcvar ("errno" +error-number+ :read-only t) :int)
  4057. @result{} +ERROR-NUMBER+
  4058. CFFI> (setf +error-number+ 12)
  4059. ;; @lispcmt{@error{} Trying to modify read-only foreign var: +ERROR-NUMBER+.}
  4060. @end lisp
  4061. @emph{Note that accessing @code{errno} this way won't work with every
  4062. implementation of the C standard library.}
  4063. @subheading See Also
  4064. @seealso{get-var-pointer}
  4065. @c ===================================================================
  4066. @c GET-VAR-POINTER
  4067. @page
  4068. @node get-var-pointer, , defcvar, Variables
  4069. @heading get-var-pointer
  4070. @subheading Syntax
  4071. @Function{get-var-pointer symbol @res{} pointer}
  4072. @subheading Arguments and Values
  4073. @table @var
  4074. @item symbol
  4075. A symbol denoting a foreign variable defined with @code{defcvar}.
  4076. @item pointer
  4077. A foreign pointer.
  4078. @end table
  4079. @subheading Description
  4080. The function @code{get-var-pointer} will return a @var{pointer} to the
  4081. foreign global variable @var{symbol} previously defined with
  4082. @code{defcvar}.
  4083. @subheading Examples
  4084. @lisp
  4085. CFFI> (defcvar "errno" :int :read-only t)
  4086. @result{} *ERRNO*
  4087. CFFI> *errno*
  4088. @result{} 25
  4089. CFFI> (get-var-pointer '*errno*)
  4090. @result{} #<A Mac Pointer #xA0008130>
  4091. CFFI> (mem-ref * :int)
  4092. @result{} 25
  4093. @end lisp
  4094. @subheading See Also
  4095. @seealso{defcvar}
  4096. @c ===================================================================
  4097. @c CHAPTER: Functions
  4098. @node Functions, Libraries, Variables, Top
  4099. @chapter Functions
  4100. @menu
  4101. @c * Defining Foreign Functions::
  4102. @c * Calling Foreign Functions::
  4103. Dictionary
  4104. * defcfun::
  4105. * foreign-funcall::
  4106. * foreign-funcall-pointer::
  4107. * foreign-funcall-varargs::
  4108. * foreign-funcall-pointer-varargs::
  4109. * translate-camelcase-name::
  4110. * translate-name-from-foreign::
  4111. * translate-name-to-foreign::
  4112. * translate-underscore-separated-name::
  4113. @end menu
  4114. @c @node Calling Foreign Functions
  4115. @c @section Calling Foreign Functions
  4116. @c @node Defining Foreign Functions
  4117. @c @section Defining Foreign Functions
  4118. @c ===================================================================
  4119. @c DEFCFUN
  4120. @page
  4121. @node defcfun, foreign-funcall, Functions, Functions
  4122. @heading defcfun
  4123. @subheading Syntax
  4124. @Macro{defcfun name-and-options return-type &body [docstring] arguments [&rest] @
  4125. @res{} lisp-name}
  4126. @var{name-and-options} ::= @var{name} | (@var{name} &key @var{library} @var{convention}) @*
  4127. @var{name} ::= @var{lisp-name} [@var{foreign-name}] | @var{foreign-name} [@var{lisp-name}] @*
  4128. @var{arguments} ::= @{ (@var{arg-name} @var{arg-type}) @}* @*
  4129. @subheading Arguments and Values
  4130. @table @var
  4131. @item foreign-name
  4132. A string denoting a foreign function.
  4133. @item lisp-name
  4134. A symbol naming the Lisp function to be created.
  4135. @item arg-name
  4136. A symbol.
  4137. @item return-type
  4138. @itemx arg-type
  4139. A foreign type.
  4140. @item convention
  4141. One of @code{:cdecl} (default) or @code{:stdcall}.
  4142. @item library
  4143. A symbol designating a foreign library.
  4144. @item docstring
  4145. A documentation string.
  4146. @end table
  4147. @subheading Description
  4148. The @code{defcfun} macro provides a declarative interface for defining
  4149. Lisp functions that call foreign functions.
  4150. When one of @var{lisp-name} or @var{foreign-name} is omitted, the
  4151. other is automatically derived using the following rules:
  4152. @itemize
  4153. @item
  4154. Foreign names are converted to Lisp names by uppercasing and replacing
  4155. underscores with hyphens.
  4156. @item
  4157. Lisp names are converted to foreign names by lowercasing and replacing
  4158. hyphens with underscores.
  4159. @end itemize
  4160. If you place the symbol @code{&rest} in the end of the argument list
  4161. after the fixed arguments, @code{defcfun} will treat the foreign
  4162. function as a @strong{variadic function}. The variadic arguments
  4163. should be passed in a way similar to what @code{foreign-funcall} would
  4164. expect. Unlike @code{foreign-funcall} though, @code{defcfun} will take
  4165. care of doing argument promotion. Note that in this case
  4166. @code{defcfun} will generate a Lisp @emph{macro} instead of a
  4167. function and will only work for Lisps that support
  4168. @code{foreign-funcall.}
  4169. If a foreign structure is to be passed or returned by value (that is,
  4170. the type is of the form @code{(:struct ...)}), then the cffi-libffi system
  4171. must be loaded, which in turn depends on
  4172. @uref{http://sourceware.org/libffi/,libffi}, including the header files.
  4173. Failure to load that system will result in an error.
  4174. Variadic functions cannot at present accept or return structures by
  4175. value.
  4176. @subheading Examples
  4177. @lisp
  4178. (defcfun "strlen" :int
  4179. "Calculate the length of a string."
  4180. (n :string))
  4181. CFFI> (strlen "123")
  4182. @result{} 3
  4183. @end lisp
  4184. @lisp
  4185. (defcfun ("abs" c-abs) :int (n :int))
  4186. CFFI> (c-abs -42)
  4187. @result{} 42
  4188. @end lisp
  4189. Function without arguments:
  4190. @lisp
  4191. (defcfun "rand" :int)
  4192. CFFI> (rand)
  4193. @result{} 1804289383
  4194. @end lisp
  4195. Variadic function example:
  4196. @lisp
  4197. (defcfun "sprintf" :int
  4198. (str :pointer)
  4199. (control :string)
  4200. &rest)
  4201. CFFI> (with-foreign-pointer-as-string (s 100)
  4202. (sprintf s "%c %d %.2f %s" :char 90 :short 42 :float pi
  4203. :string "super-locrian"))
  4204. @result{} "A 42 3.14 super-locrian"
  4205. @end lisp
  4206. @subheading See Also
  4207. @seealso{foreign-funcall} @*
  4208. @seealso{foreign-funcall-pointer} @*
  4209. @seealso{foreign-funcall-varargs} @*
  4210. @seealso{foreign-funcall-pointer-varargs}
  4211. @c ===================================================================
  4212. @c FOREIGN-FUNCALL
  4213. @page
  4214. @node foreign-funcall, foreign-funcall-pointer, defcfun, Functions
  4215. @heading foreign-funcall
  4216. @subheading Syntax
  4217. @Macro{foreign-funcall name-and-options &rest arguments @res{} return-value}
  4218. @var{arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
  4219. @var{name-and-options} ::= @var{name} | (@var{name} &key @var{library} @var{convention}) @*
  4220. @subheading Arguments and Values
  4221. @table @var
  4222. @item name
  4223. A Lisp string.
  4224. @item arg-type
  4225. A foreign type.
  4226. @item arg
  4227. An argument of type @var{arg-type}.
  4228. @item return-type
  4229. A foreign type, @code{:void} by default.
  4230. @item return-value
  4231. A lisp object.
  4232. @item library
  4233. A lisp symbol; not evaluated.
  4234. @item convention
  4235. One of @code{:cdecl} (default) or @code{:stdcall}.
  4236. @end table
  4237. @subheading Description
  4238. The @code{foreign-funcall} macro is the main primitive for calling
  4239. foreign functions.
  4240. If a foreign structure is to be passed or returned by value (that is,
  4241. the type is of the form @code{(:struct ...)}), then the cffi-libffi system
  4242. must be loaded, which in turn depends on
  4243. @uref{http://sourceware.org/libffi/,libffi}, including the header files.
  4244. Failure to load that system will result in an error.
  4245. Variadic functions cannot at present accept or return structures by
  4246. value.
  4247. @emph{Note: The return value of foreign-funcall on functions with a
  4248. :void return type is still undefined.}
  4249. @subheading Implementation-specific Notes
  4250. @itemize
  4251. @item
  4252. Corman Lisp does not support @code{foreign-funcall}. On
  4253. implementations that @strong{don't} support @code{foreign-funcall}
  4254. @code{cffi-sys::no-foreign-funcall} will be present in
  4255. @code{*features*}. Note: in these Lisps you can still use the
  4256. @code{defcfun} interface.
  4257. @end itemize
  4258. @subheading Examples
  4259. @lisp
  4260. CFFI> (foreign-funcall "strlen" :string "foo" :int)
  4261. @result{} 3
  4262. @end lisp
  4263. Given the C code:
  4264. @example
  4265. void print_number(int n)
  4266. @{
  4267. printf("N: %d\n", n);
  4268. @}
  4269. @end example
  4270. @lisp
  4271. CFFI> (foreign-funcall "print_number" :int 123456)
  4272. @print{} N: 123456
  4273. @result{} NIL
  4274. @end lisp
  4275. @noindent
  4276. Or, equivalently:
  4277. @lisp
  4278. CFFI> (foreign-funcall "print_number" :int 123456 :void)
  4279. @print{} N: 123456
  4280. @result{} NIL
  4281. @end lisp
  4282. @lisp
  4283. CFFI> (foreign-funcall "printf" :string (format nil "%s: %d.~%")
  4284. :string "So long and thanks for all the fish"
  4285. :int 42 :int)
  4286. @print{} So long and thanks for all the fish: 42.
  4287. @result{} 41
  4288. @end lisp
  4289. @subheading See Also
  4290. @seealso{defcfun} @*
  4291. @seealso{foreign-funcall-pointer}
  4292. @c ===================================================================
  4293. @c FOREIGN-FUNCALL-POINTER
  4294. @page
  4295. @node foreign-funcall-pointer, foreign-funcall-varargs, foreign-funcall, Functions
  4296. @heading foreign-funcall-pointer
  4297. @subheading Syntax
  4298. @Macro{foreign-funcall-pointer pointer options &rest arguments @res{} return-value}
  4299. @var{arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
  4300. @var{options} ::= (&key @var{convention}) @*
  4301. @subheading Arguments and Values
  4302. @table @var
  4303. @item pointer
  4304. A foreign pointer.
  4305. @item arg-type
  4306. A foreign type.
  4307. @item arg
  4308. An argument of type @var{arg-type}.
  4309. @item return-type
  4310. A foreign type, @code{:void} by default.
  4311. @item return-value
  4312. A lisp object.
  4313. @item convention
  4314. One of @code{:cdecl} (default) or @code{:stdcall}.
  4315. @end table
  4316. @subheading Description
  4317. The @code{foreign-funcall} macro is the main primitive for calling
  4318. foreign functions.
  4319. @emph{Note: The return value of foreign-funcall on functions with a
  4320. :void return type is still undefined.}
  4321. @subheading Implementation-specific Notes
  4322. @itemize
  4323. @item
  4324. Corman Lisp does not support @code{foreign-funcall}. On
  4325. implementations that @strong{don't} support @code{foreign-funcall}
  4326. @code{cffi-sys::no-foreign-funcall} will be present in
  4327. @code{*features*}. Note: in these Lisps you can still use the
  4328. @code{defcfun} interface.
  4329. @end itemize
  4330. @subheading Examples
  4331. @lisp
  4332. CFFI> (foreign-funcall-pointer (foreign-symbol-pointer "abs") ()
  4333. :int -42 :int)
  4334. @result{} 42
  4335. @end lisp
  4336. @subheading See Also
  4337. @seealso{defcfun} @*
  4338. @seealso{foreign-funcall}
  4339. @c ===================================================================
  4340. @c FOREIGN-FUNCALL-VARARGS
  4341. @page
  4342. @node foreign-funcall-varargs, foreign-funcall-pointer-varargs, foreign-funcall-pointer, Functions
  4343. @heading foreign-funcall-varargs
  4344. @subheading Syntax
  4345. @Macro{foreign-funcall-varargs name-and-options (fixed-arguments) &rest arguments @res{} return-value}
  4346. @var{fixed-arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
  4347. @var{arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
  4348. @var{name-and-options} ::= @var{name} | (@var{name} &key @var{library} @var{convention}) @*
  4349. @subheading Arguments and Values
  4350. @table @var
  4351. @item name
  4352. A Lisp string.
  4353. @item arg-type
  4354. A foreign type.
  4355. @item arg
  4356. An argument of type @var{arg-type}.
  4357. @item return-type
  4358. A foreign type, @code{:void} by default.
  4359. @item return-value
  4360. A lisp object.
  4361. @item library
  4362. A lisp symbol; not evaluated.
  4363. @item convention
  4364. One of @code{:cdecl} (default) or @code{:stdcall}.
  4365. @end table
  4366. @subheading Description
  4367. The @code{foreign-funcall-varargs} macro is the main primitive for
  4368. calling foreign variadic functions. It behaves similarily to
  4369. @code{foreign-funcall} except @code{fixed-arguments} are distinguished
  4370. from the remaining arguments.
  4371. @subheading Examples
  4372. @lisp
  4373. CFFI> (with-foreign-pointer-as-string (s 100)
  4374. (setf (mem-ref s :char) 0)
  4375. (foreign-funcall-varargs
  4376. "sprintf" (:pointer s :string) "%.2f")
  4377. :double (coerce pi 'double-float) :int))
  4378. @result{} 3.14
  4379. @end lisp
  4380. @c ===================================================================
  4381. @c FOREIGN-FUNCALL-POINTER-VARARGS
  4382. @page
  4383. @node foreign-funcall-pointer-varargs, translate-camelcase-name, foreign-funcall-varargs, Functions
  4384. @heading foreign-funcall-pointer-varargs
  4385. @subheading Syntax
  4386. @Macro{foreign-funcall-pointer-varargs pointer options (fixed-arguments) &rest arguments @res{} return-value}
  4387. @var{fixed-arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
  4388. @var{arguments} ::= @{ @var{arg-type} @var{arg} @}* [@var{return-type}] @*
  4389. @var{options} ::= (&key @var{convention}) @*
  4390. @subheading Arguments and Values
  4391. @table @var
  4392. @item pointer
  4393. A foreign pointer.
  4394. @item arg-type
  4395. A foreign type.
  4396. @item arg
  4397. An argument of type @var{arg-type}.
  4398. @item return-type
  4399. A foreign type, @code{:void} by default.
  4400. @item return-value
  4401. A lisp object.
  4402. @item convention
  4403. One of @code{:cdecl} (default) or @code{:stdcall}.
  4404. @end table
  4405. @subheading Description
  4406. The @code{foreign-funcall-pointer-varargs} macro is the main primitive
  4407. for calling foreign variadic functions. It behaves similarily to
  4408. @code{foreign-funcall-pointer} except @code{fixed-arguments} are
  4409. distinguished from the remaining arguments.
  4410. @subheading Examples
  4411. @lisp
  4412. CFFI> (with-foreign-pointer-as-string (s 100)
  4413. (setf (mem-ref s :char) 0)
  4414. (foreign-funcall-pointer-varargs
  4415. (foreign-symbol-pointer "sprintf") () (:pointer s :string "%.2f")
  4416. :double (coerce pi 'double-float) :int))
  4417. @result{} 3.14
  4418. @end lisp
  4419. @c ===================================================================
  4420. @c TRANSLATE-CAMELCASE-NAME
  4421. @page
  4422. @node translate-camelcase-name, translate-name-from-foreign, foreign-funcall-pointer-varargs, Functions
  4423. @heading translate-camelcase-name
  4424. @subheading Syntax
  4425. @Function{translate-camelcase-name name &key upper-initial-p special-words @res{} return-value}
  4426. @subheading Arguments and Values
  4427. @table @var
  4428. @item name
  4429. Either a symbol or a string.
  4430. @item upper-initial-p
  4431. A generalized boolean.
  4432. @item special words
  4433. A list of strings.
  4434. @item return-value
  4435. If @var{name} is a symbol, this is a string, and vice versa.
  4436. @end table
  4437. @subheading Description
  4438. @code{translate-camelcase-name} is a helper function for
  4439. specializations of @code{translate-name-from-foreign} and
  4440. @code{translate-name-to-foreign}. It handles the common case of
  4441. converting between foreign camelCase names and lisp
  4442. names. @var{upper-initial-p} indicates whether the first letter of the
  4443. foreign name should be uppercase. @var{special-words} is a list of
  4444. strings that should be treated atomically in translation. This list is
  4445. case-sensitive.
  4446. @subheading Examples
  4447. @lisp
  4448. CFFI> (translate-camelcase-name some-xml-function)
  4449. @result{} "someXmlFunction"
  4450. CFFI> (translate-camelcase-name some-xml-function :upper-initial-p t)
  4451. @result{} "SomeXmlFunction"
  4452. CFFI> (translate-camelcase-name some-xml-function :special-words '("XML"))
  4453. @result{} "someXMLFunction"
  4454. CFFI> (translate-camelcase-name "someXMLFunction")
  4455. @result{} SOME-X-M-L-FUNCTION
  4456. CFFI> (translate-camelcase-name "someXMLFunction" :special-words '("XML"))
  4457. @result{} SOME-XML-FUNCTION
  4458. @end lisp
  4459. @subheading See Also
  4460. @seealso{translate-name-from-foreign} @*
  4461. @seealso{translate-name-to-foreign} @*
  4462. @seealso{translate-underscore-separated-name}
  4463. @c ===================================================================
  4464. @c TRANSLATE-NAME-FROM-FOREIGN
  4465. @page
  4466. @node translate-name-from-foreign, translate-name-to-foreign, translate-camelcase-name, Functions
  4467. @heading translate-name-from-foreign
  4468. @subheading Syntax
  4469. @Function{translate-name-from-foreign foreign-name package &optional varp @res{} symbol}
  4470. @subheading Arguments and Values
  4471. @table @var
  4472. @item foreign-name
  4473. A string denoting a foreign function.
  4474. @item package
  4475. A Lisp package
  4476. @item varp
  4477. A generalized boolean.
  4478. @item symbol
  4479. The Lisp symbol to be used a function name.
  4480. @end table
  4481. @subheading Description
  4482. @code{translate-name-from-foreign} is used by @ref{defcfun} to handle
  4483. the conversion of foreign names to lisp names. By default, it
  4484. translates using @ref{translate-underscore-separated-name}. However,
  4485. you can create specialized methods on this function to make
  4486. translating more closely match the foreign library's naming
  4487. conventions.
  4488. Specialize @var{package} on some package. This allows other packages
  4489. to load libraries with different naming conventions.
  4490. @subheading Examples
  4491. @lisp
  4492. CFFI> (defcfun "someXmlFunction" ...)
  4493. @result{} SOMEXMLFUNCTION
  4494. CFFI> (defmethod translate-name-from-foreign ((spec string)
  4495. (package (eql *package*))
  4496. &optional varp)
  4497. (let ((name (translate-camelcase-name spec)))
  4498. (if varp (intern (format nil "*~a*" name)) name)))
  4499. @result{} #<STANDARD-METHOD TRANSLATE-NAME-FROM-FOREIGN (STRING (EQL #<Package "SOME-PACKAGE">))>
  4500. CFFI> (defcfun "someXmlFunction" ...)
  4501. @result{} SOME-XML-FUNCTION
  4502. @end lisp
  4503. @subheading See Also
  4504. @seealso{defcfun} @*
  4505. @seealso{translate-camelcase-name} @*
  4506. @seealso{translate-name-to-foreign} @*
  4507. @seealso{translate-underscore-separated-name}
  4508. @c ===================================================================
  4509. @c TRANSLATE-NAME-TO-FOREIGN
  4510. @page
  4511. @node translate-name-to-foreign, translate-underscore-separated-name, translate-name-from-foreign, Functions
  4512. @heading translate-name-to-foreign
  4513. @subheading Syntax
  4514. @Function{translate-name-to-foreign lisp-name package &optional varp @res{} string}
  4515. @subheading Arguments and Values
  4516. @table @var
  4517. @item lisp-name
  4518. A symbol naming the Lisp function to be created.
  4519. @item package
  4520. A Lisp package
  4521. @item varp
  4522. A generalized boolean.
  4523. @item string
  4524. The string representing the foreign function name.
  4525. @end table
  4526. @subheading Description
  4527. @code{translate-name-to-foreign} is used by @ref{defcfun} to handle
  4528. the conversion of lisp names to foreign names. By default, it
  4529. translates using @ref{translate-underscore-separated-name}. However,
  4530. you can create specialized methods on this function to make
  4531. translating more closely match the foreign library's naming
  4532. conventions.
  4533. Specialize @var{package} on some package. This allows other packages
  4534. to load libraries with different naming conventions.
  4535. @subheading Examples
  4536. @lisp
  4537. CFFI> (defcfun some-xml-function ...)
  4538. @result{} "some_xml_function"
  4539. CFFI> (defmethod translate-name-to-foreign ((spec symbol)
  4540. (package (eql *package*))
  4541. &optional varp)
  4542. (let ((name (translate-camelcase-name spec)))
  4543. (if varp (subseq name 1 (1- (length name))) name)))
  4544. @result{} #<STANDARD-METHOD TRANSLATE-NAME-TO-FOREIGN (STRING (EQL #<Package "SOME-PACKAGE">))>
  4545. CFFI> (defcfun some-xml-function ...)
  4546. @result{} "someXmlFunction"
  4547. @end lisp
  4548. @subheading See Also
  4549. @seealso{defcfun} @*
  4550. @seealso{translate-camelcase-name} @*
  4551. @seealso{translate-name-from-foreign} @*
  4552. @seealso{translate-underscore-separated-name}
  4553. @c ===================================================================
  4554. @c TRANSLATE-UNDERSCORE-SEPARATED-NAME
  4555. @page
  4556. @node translate-underscore-separated-name, , translate-name-to-foreign, Functions
  4557. @heading translate-underscore-separated-name
  4558. @subheading Syntax
  4559. @Function{translate-underscore-separated-name name @res{} return-value}
  4560. @subheading Arguments and Values
  4561. @table @var
  4562. @item name
  4563. Either a symbol or a string.
  4564. @item return-value
  4565. If @var{name} is a symbol, this is a string, and vice versa.
  4566. @end table
  4567. @subheading Description
  4568. @code{translate-underscore-separated-name} is a helper function for
  4569. specializations of @ref{translate-name-from-foreign} and
  4570. @ref{translate-name-to-foreign}. It handles the common case of
  4571. converting between foreign underscore_separated names and lisp names.
  4572. @subheading Examples
  4573. @lisp
  4574. CFFI> (translate-underscore-separated-name some-xml-function)
  4575. @result{} "some_xml_function"
  4576. CFFI> (translate-camelcase-name "some_xml_function")
  4577. @result{} SOME-XML-FUNCTION
  4578. @end lisp
  4579. @subheading See Also
  4580. @seealso{translate-name-from-foreign} @*
  4581. @seealso{translate-name-to-foreign} @*
  4582. @seealso{translate-camelcase-name}
  4583. @c ===================================================================
  4584. @c CHAPTER: Libraries
  4585. @node Libraries, Callbacks, Functions, Top
  4586. @chapter Libraries
  4587. @menu
  4588. * Defining a library::
  4589. * Library definition style::
  4590. Dictionary
  4591. * close-foreign-library:: Close a foreign library.
  4592. * *darwin-framework-directories*:: Search path for Darwin frameworks.
  4593. * define-foreign-library:: Explain how to load a foreign library.
  4594. * *foreign-library-directories*:: Search path for shared libraries.
  4595. * load-foreign-library:: Load a foreign library.
  4596. * load-foreign-library-error:: Signalled on failure of its namesake.
  4597. * use-foreign-library:: Load a foreign library when needed.
  4598. @end menu
  4599. @node Defining a library, Library definition style, Libraries, Libraries
  4600. @section Defining a library
  4601. Almost all foreign code you might want to access exists in some kind
  4602. of shared library. The meaning of @dfn{shared library} varies among
  4603. platforms, but for our purposes, we will consider it to include
  4604. @file{.so} files on @sc{unix}, frameworks on Darwin (and derivatives
  4605. like Mac @acronym{OS X}), and @file{.dll} files on Windows.
  4606. Bringing one of these libraries into the Lisp image is normally a
  4607. two-step process.
  4608. @enumerate
  4609. @item
  4610. Describe to @cffi{} how to load the library at some future point,
  4611. depending on platform and other factors, with a
  4612. @code{define-foreign-library} top-level form.
  4613. @item
  4614. Load the library so defined with either a top-level
  4615. @code{use-foreign-library} form or by calling the function
  4616. @code{load-foreign-library}.
  4617. @end enumerate
  4618. @xref{Tutorial-Loading,, Loading foreign libraries}, for a working
  4619. example of the above two steps.
  4620. @node Library definition style, close-foreign-library, Defining a library, Libraries
  4621. @section Library definition style
  4622. Looking at the @code{libcurl} library definition presented earlier,
  4623. you may ask why we did not simply do this:
  4624. @lisp
  4625. (define-foreign-library libcurl
  4626. (t (:default "libcurl")))
  4627. @end lisp
  4628. @noindent
  4629. Indeed, this would work just as well on the computer on which I tested
  4630. the tutorial. There are a couple of good reasons to provide the
  4631. @file{.so}'s current version number, however. Namely, the versionless
  4632. @file{.so} is not packaged on most @sc{unix} systems along with the
  4633. actual, fully-versioned library; instead, it is included in the
  4634. ``development'' package along with C headers and static @file{.a}
  4635. libraries.
  4636. The reason @cffi{} does not try to account for this lies in the
  4637. meaning of the version numbers. A full treatment of shared library
  4638. versions is beyond this manual's scope; see @ref{Versioning,, Library
  4639. interface versions, libtool, @acronym{GNU} Libtool}, for helpful
  4640. information for the unfamiliar. For our purposes, consider that a
  4641. mismatch between the library version with which you tested and the
  4642. installed library version may cause undefined
  4643. behavior.@footnote{Windows programmers may chafe at adding a
  4644. @sc{unix}-specific clause to @code{define-foreign-library}. Instead,
  4645. ask why the Windows solution to library incompatibility is ``include
  4646. your own version of every library you use with every program''.}
  4647. @impnote{Maybe some notes should go here about OS X, which I know
  4648. little about. --stephen}
  4649. @c ===================================================================
  4650. @c CLOSE-FOREIGN-LIBRARY
  4651. @page
  4652. @node close-foreign-library, *darwin-framework-directories*, Library definition style, Libraries
  4653. @heading close-foreign-library
  4654. @subheading Syntax
  4655. @Function{close-foreign-library library @res{} success}
  4656. @subheading Arguments and Values
  4657. @table @var
  4658. @item library
  4659. A symbol or an instance of @code{foreign-library}.
  4660. @item success
  4661. A Lisp boolean.
  4662. @end table
  4663. @subheading Description
  4664. Closes @var{library} which can be a symbol designating a library
  4665. define through @code{define-foreign-library} or an instance of
  4666. @code{foreign-library} as returned by @code{load-foreign-library}.
  4667. @c @subheading Examples
  4668. @c @xref{Tutorial-Loading,, Loading foreign libraries}.
  4669. @subheading See Also
  4670. @seealso{define-foreign-library} @*
  4671. @seealso{load-foreign-library} @*
  4672. @seealso{use-foreign-library}
  4673. @c ===================================================================
  4674. @c *DARWIN-FRAMEWORK-DIRECTORIES*
  4675. @page
  4676. @node *darwin-framework-directories*, define-foreign-library, close-foreign-library, Libraries
  4677. @heading *darwin-framework-directories*
  4678. @subheading Syntax
  4679. @Variable{*darwin-framework-directories*}
  4680. @subheading Value type
  4681. A list, in which each element is a string, a pathname, or a simple
  4682. Lisp expression.
  4683. @subheading Initial value
  4684. A list containing the following, in order: an expression corresponding
  4685. to Darwin path @file{~/Library/Frameworks/},
  4686. @code{#P"/Library/Frameworks/"}, and
  4687. @code{#P"/System/Library/Frameworks/"}.
  4688. @subheading Description
  4689. The meaning of ``simple Lisp expression'' is explained in
  4690. @ref{*foreign-library-directories*}. In contrast to that variable,
  4691. this is not a fallback search path; the default value described above
  4692. is intended to be a reasonably complete search path on Darwin systems.
  4693. @subheading Examples
  4694. @lisp
  4695. CFFI> (let ((lib (load-foreign-library '(:framework "OpenGL"))))
  4696. (foreign-library-pathname lib))
  4697. @result{} #P"/System/Library/Frameworks/OpenGL.framework/OpenGL"
  4698. @end lisp
  4699. @subheading See also
  4700. @seealso{*foreign-library-directories*} @*
  4701. @seealso{define-foreign-library}
  4702. @c ===================================================================
  4703. @c DEFINE-FOREIGN-LIBRARY
  4704. @page
  4705. @node define-foreign-library, *foreign-library-directories*, *darwin-framework-directories*, Libraries
  4706. @heading define-foreign-library
  4707. @subheading Syntax
  4708. @Macro{define-foreign-library name-and-options @{ load-clause @}* @res{} name}
  4709. name-and-options ::= name | (name &key canary convention search-path) @*
  4710. load-clause ::= (feature library &key convention search-path) @*
  4711. @subheading Arguments and Values
  4712. @table @var
  4713. @item name
  4714. A symbol.
  4715. @item feature
  4716. A feature expression.
  4717. @item library
  4718. A library designator.
  4719. @item canary
  4720. A string denoting a foreign symbol that will be searched in core
  4721. before attempting to load the library. If that symbol is found, the
  4722. library is assumed to be statically linked and
  4723. @code{load-foreign-library} only marks the library as loaded.
  4724. Some implementations (Clisp, ECL, SBCL) natively support static
  4725. linking, sometimes referred to as a @emph{link kit}.
  4726. @item convention
  4727. One of @code{:cdecl} (default) or @code{:stdcall}
  4728. @item search-path
  4729. A path or list of paths where the library will be searched if not found in
  4730. system-global directories. Paths specified in a load clause take priority over
  4731. paths specified as library option, with *foreign-library-directories* having
  4732. lowest priority.
  4733. @end table
  4734. @subheading Description
  4735. Creates a new library designator called @var{name}. The
  4736. @var{load-clause}s describe how to load that designator when passed to
  4737. @code{load-foreign-library} or @code{use-foreign-library}.
  4738. When trying to load the library @var{name}, the relevant function
  4739. searches the @var{load-clause}s in order for the first one where
  4740. @var{feature} evaluates to true. That happens for any of the
  4741. following situations:
  4742. @enumerate 1
  4743. @item
  4744. If @var{feature} is a symbol present in @code{common-lisp:*features*}.
  4745. @item
  4746. If @var{feature} is a list, depending on @code{(first @var{feature})},
  4747. a keyword:
  4748. @table @code
  4749. @item :and
  4750. All of the feature expressions in @code{(rest @var{feature})} are
  4751. true.
  4752. @item :or
  4753. At least one of the feature expressions in @code{(rest @var{feature})}
  4754. is true.
  4755. @item :not
  4756. The feature expression @code{(second @var{feature})} is not true.
  4757. @end table
  4758. @item
  4759. Finally, if @var{feature} is @code{t}, this @var{load-clause} is
  4760. picked unconditionally.
  4761. @end enumerate
  4762. Upon finding the first true @var{feature}, the library loader then
  4763. loads the @var{library}. The meaning of ``library designator'' is
  4764. described in @ref{load-foreign-library}.
  4765. Functions associated to a library defined by
  4766. @code{define-foreign-library} (e.g. through @code{defcfun}'s
  4767. @code{:library} option, will inherit the library's options. The
  4768. precedence is as follows:
  4769. @enumerate 1
  4770. @item
  4771. @code{defcfun}/@code{foreign-funcall} specific options;
  4772. @item
  4773. @var{load-clause} options;
  4774. @item
  4775. global library options (the @var{name-and-options} argument)
  4776. @end enumerate
  4777. @subheading Examples
  4778. @xref{Tutorial-Loading,, Loading foreign libraries}.
  4779. @subheading See Also
  4780. @seealso{close-foreign-library} @*
  4781. @seealso{load-foreign-library}
  4782. @c ===================================================================
  4783. @c *FOREIGN-LIBRARY-DIRECTORIES*
  4784. @page
  4785. @node *foreign-library-directories*, load-foreign-library, define-foreign-library, Libraries
  4786. @heading *foreign-library-directories*
  4787. @subheading Syntax
  4788. @Variable{*foreign-library-directories*}
  4789. @subheading Value type
  4790. A list, in which each element is a string, a pathname, or a simple
  4791. Lisp expression.
  4792. @subheading Initial value
  4793. The empty list.
  4794. @subheading Description
  4795. You should not have to use this variable.
  4796. Most, if not all, Lisps supported by @cffi{} have a reasonable default
  4797. search algorithm for foreign libraries. For example, Lisps for
  4798. @sc{unix} usually call
  4799. @uref{http://www.opengroup.org/onlinepubs/009695399/functions/dlopen.html,,
  4800. @code{dlopen(3)}}, which in turn looks in the system library
  4801. directories. Only if that fails does @cffi{} look for the named
  4802. library file in these directories, and load it from there if found.
  4803. Thus, this is intended to be a @cffi{}-only fallback to the library
  4804. search configuration provided by your operating system. For example,
  4805. if you distribute a foreign library with your Lisp package, you can
  4806. add the library's containing directory to this list and portably
  4807. expect @cffi{} to find it.
  4808. A @dfn{simple Lisp expression} is intended to provide functionality
  4809. commonly used in search paths such as
  4810. @acronym{ASDF}'s@footnote{@xref{Using asdf to load systems,,, asdf,
  4811. asdf: another system definition facility}, for information on
  4812. @code{asdf:*central-registry*}.}, and is defined recursively as
  4813. follows:@footnote{See @code{mini-eval} in @file{libraries.lisp} for
  4814. the source of this definition. As is always the case with a Lisp
  4815. @code{eval}, it's easier to understand the Lisp definition than the
  4816. english.}
  4817. @enumerate
  4818. @item
  4819. A list, whose @samp{first} is a function designator, and whose
  4820. @samp{rest} is a list of simple Lisp expressions to be evaluated and
  4821. passed to the so-designated function. The result is the result of the
  4822. function call.
  4823. @item
  4824. A symbol, whose result is its symbol value.
  4825. @item
  4826. Anything else evaluates to itself.
  4827. @end enumerate
  4828. The result of evaluating the @dfn{simple Lisp expression} should yield
  4829. a @emph{designator} for a @emph{list} of @emph{pathname designators}.
  4830. @strong{Note}: in Common Lisp, @code{#p"/foo/bar"} designates the
  4831. @emph{bar} file within the @emph{/foo} directory whereas
  4832. @code{#p"/foo/bar/"} designates the @emph{/foo/bar} directory. Keep
  4833. that in mind when customising the value of
  4834. @code{*foreign-library-directories*}.
  4835. @subheading Examples
  4836. @example
  4837. $ ls
  4838. @print{} liblibli.so libli.lisp
  4839. @end example
  4840. @noindent
  4841. In @file{libli.lisp}:
  4842. @lisp
  4843. (pushnew #P"/home/sirian/lisp/libli/" *foreign-library-directories*
  4844. :test #'equal)
  4845. (load-foreign-library '(:default "liblibli"))
  4846. @end lisp
  4847. @noindent
  4848. The following example would achieve the same effect:
  4849. @lisp
  4850. (pushnew '(merge-pathnames #p"lisp/libli/" (user-homedir-pathname))
  4851. *foreign-library-directories*
  4852. :test #'equal)
  4853. @result{} ((MERGE-PATHNAMES #P"lisp/libli/" (USER-HOMEDIR-PATHNAME)))
  4854. (load-foreign-library '(:default "liblibli"))
  4855. @end lisp
  4856. @subheading See also
  4857. @seealso{*darwin-framework-directories*} @*
  4858. @seealso{define-foreign-library}
  4859. @c ===================================================================
  4860. @c LOAD-FOREIGN-LIBRARY
  4861. @page
  4862. @node load-foreign-library, load-foreign-library-error, *foreign-library-directories*, Libraries
  4863. @heading load-foreign-library
  4864. @subheading Syntax
  4865. @Function{load-foreign-library library-designator @res{} library}
  4866. @subheading Arguments and Values
  4867. @table @var
  4868. @item library-designator
  4869. A library designator.
  4870. @item library-designator
  4871. An instance of @code{foreign-library}.
  4872. @end table
  4873. @subheading Description
  4874. Load the library indicated by @var{library-designator}. A @dfn{library
  4875. designator} is defined as follows:
  4876. @enumerate
  4877. @item
  4878. If a symbol, is considered a name previously defined with
  4879. @code{define-foreign-library}.
  4880. @item
  4881. If a string or pathname, passed as a namestring directly to the
  4882. implementation's foreign library loader. If that fails, search the
  4883. directories in @code{*foreign-library-directories*} with
  4884. @code{cl:probe-file}; if found, the absolute path is passed to the
  4885. implementation's loader.
  4886. @item
  4887. If a list, the meaning depends on @code{(first @var{library})}:
  4888. @table @code
  4889. @item :framework
  4890. The second list element is taken to be a Darwin framework name, which
  4891. is then searched in @code{*darwin-framework-directories*}, and loaded
  4892. when found.
  4893. @item :or
  4894. Each remaining list element, itself a @dfn{library designator}, is loaded in
  4895. order, until one succeeds.
  4896. @item :default
  4897. The name is transformed according to the platform's naming convention
  4898. to shared libraries, and the resultant string is loaded as a @dfn{library
  4899. designator}. For example, on @sc{unix}, the name is suffixed with
  4900. @file{.so}.
  4901. @end table
  4902. @end enumerate
  4903. If the library is already loaded it will be reloaded.
  4904. If the load fails, signal a @code{load-foreign-library-error}.
  4905. @strong{Please note:} For system libraries, you should not need to
  4906. specify the directory containing the library. Each operating system
  4907. has its own idea of a default search path, and you should rely on it
  4908. when it is reasonable.
  4909. @subheading Implementation-specific Notes
  4910. On ECL platforms where its dynamic FFI is not supported (ie. when
  4911. @code{:dffi} is not present in @code{*features*}),
  4912. @code{cffi:load-foreign-library} does not work and you must use ECL's
  4913. own @code{ffi:load-foreign-library} with a constant string argument.
  4914. @subheading Examples
  4915. @xref{Tutorial-Loading,, Loading foreign libraries}.
  4916. @subheading See Also
  4917. @seealso{close-foreign-library} @*
  4918. @seealso{*darwin-framework-directories*} @*
  4919. @seealso{define-foreign-library} @*
  4920. @seealso{*foreign-library-directories*} @*
  4921. @seealso{load-foreign-library-error} @*
  4922. @seealso{use-foreign-library}
  4923. @c ===================================================================
  4924. @c LOAD-FOREIGN-LIBRARY-ERROR
  4925. @page
  4926. @node load-foreign-library-error, use-foreign-library, load-foreign-library, Libraries
  4927. @heading load-foreign-library-error
  4928. @subheading Syntax
  4929. @Condition{load-foreign-library-error}
  4930. @subheading Class precedence list
  4931. @code{load-foreign-library-error}, @code{error},
  4932. @code{serious-condition}, @code{condition}, @code{t}
  4933. @subheading Description
  4934. Signalled when a foreign library load completely fails. The exact
  4935. meaning of this varies depending on the real conditions at work, but
  4936. almost universally, the implementation's error message is useless.
  4937. However, @cffi{} does provide the useful restarts @code{retry} and
  4938. @code{use-value}; invoke the @code{retry} restart to try loading the
  4939. foreign library again, or the @code{use-value} restart to try loading
  4940. a different foreign library designator.
  4941. @subheading See also
  4942. @seealso{load-foreign-library}
  4943. @c ===================================================================
  4944. @c USE-FOREIGN-LIBRARY
  4945. @page
  4946. @node use-foreign-library, , load-foreign-library-error, Libraries
  4947. @heading use-foreign-library
  4948. @subheading Syntax
  4949. @Macro{use-foreign-library name}
  4950. @subheading Arguments and values
  4951. @table @var
  4952. @item name
  4953. A library designator; unevaluated.
  4954. @end table
  4955. @subheading Description
  4956. @xref{load-foreign-library}, for the meaning of ``library
  4957. designator''. This is intended to be the top-level form used
  4958. idiomatically after a @code{define-foreign-library} form to go ahead
  4959. and load the library. @c ; it also sets the ``current foreign library''.
  4960. Finally, on implementations where the regular evaluation rule is
  4961. insufficient for foreign library loading, it loads it at the required
  4962. time.@footnote{Namely, @acronym{CMUCL}. See
  4963. @code{use-foreign-library} in @file{libraries.lisp} for details.}
  4964. @c current foreign library is a concept created a few hours ago as of
  4965. @c this writing. It is not actually used yet, but probably will be.
  4966. @subheading Examples
  4967. @xref{Tutorial-Loading,, Loading foreign libraries}.
  4968. @subheading See also
  4969. @seealso{load-foreign-library}
  4970. @c ===================================================================
  4971. @c CHAPTER: Callbacks
  4972. @node Callbacks, The Groveller, Libraries, Top
  4973. @chapter Callbacks
  4974. @menu
  4975. Dictionary
  4976. * callback::
  4977. * defcallback::
  4978. * get-callback::
  4979. @end menu
  4980. @c ===================================================================
  4981. @c CALLBACK
  4982. @page
  4983. @node callback, defcallback, Callbacks, Callbacks
  4984. @heading callback
  4985. @subheading Syntax
  4986. @Macro{callback symbol @res{} pointer}
  4987. @subheading Arguments and Values
  4988. @table @var
  4989. @item symbol
  4990. A symbol denoting a callback.
  4991. @item pointer
  4992. @itemx new-value
  4993. A pointer.
  4994. @end table
  4995. @subheading Description
  4996. The @code{callback} macro is analogous to the standard CL special
  4997. operator @code{function} and will return a pointer to the callback
  4998. denoted by the symbol @var{name}.
  4999. @subheading Examples
  5000. @lisp
  5001. CFFI> (defcallback sum :int ((a :int) (b :int))
  5002. (+ a b))
  5003. @result{} SUM
  5004. CFFI> (callback sum)
  5005. @result{} #<A Mac Pointer #x102350>
  5006. @end lisp
  5007. @subheading See Also
  5008. @seealso{get-callback} @*
  5009. @seealso{defcallback}
  5010. @c ===================================================================
  5011. @c DEFCALLBACK
  5012. @page
  5013. @node defcallback, get-callback, callback, Callbacks
  5014. @heading defcallback
  5015. @subheading Syntax
  5016. @Macro{defcallback name-and-options return-type arguments &body body @res{} name}
  5017. name-and-options ::= name | (name &key convention) @*
  5018. arguments ::= (@{ (arg-name arg-type) @}*) @*
  5019. @subheading Arguments and Values
  5020. @table @var
  5021. @item name
  5022. A symbol naming the callback created.
  5023. @item return-type
  5024. The foreign type for the callback's return value.
  5025. @item arg-name
  5026. A symbol.
  5027. @item arg-type
  5028. A foreign type.
  5029. @item convention
  5030. One of @code{:cdecl} (default) or @code{:stdcall}.
  5031. @end table
  5032. @subheading Description
  5033. The @code{defcallback} macro defines a Lisp function that can be called
  5034. from C. The arguments passed to this function will be converted to the
  5035. appropriate Lisp representation and its return value will be converted
  5036. to its C representation.
  5037. This Lisp function can be accessed by the @code{callback} macro or the
  5038. @code{get-callback} function.
  5039. @strong{Portability note:} @code{defcallback} will not work correctly
  5040. on some Lisps if it's not a top-level form.
  5041. @subheading Examples
  5042. @lisp
  5043. (defcfun "qsort" :void
  5044. (base :pointer)
  5045. (nmemb :int)
  5046. (size :int)
  5047. (fun-compar :pointer))
  5048. (defcallback < :int ((a :pointer) (b :pointer))
  5049. (let ((x (mem-ref a :int))
  5050. (y (mem-ref b :int)))
  5051. (cond ((> x y) 1)
  5052. ((< x y) -1)
  5053. (t 0))))
  5054. CFFI> (with-foreign-object (array :int 10)
  5055. ;; @lispcmt{Initialize array.}
  5056. (loop for i from 0 and n in '(7 2 10 4 3 5 1 6 9 8)
  5057. do (setf (mem-aref array :int i) n))
  5058. ;; @lispcmt{Sort it.}
  5059. (qsort array 10 (foreign-type-size :int) (callback <))
  5060. ;; @lispcmt{Return it as a list.}
  5061. (loop for i from 0 below 10
  5062. collect (mem-aref array :int i)))
  5063. @result{} (1 2 3 4 5 6 7 8 9 10)
  5064. @end lisp
  5065. @subheading See Also
  5066. @seealso{callback} @*
  5067. @seealso{get-callback}
  5068. @c ===================================================================
  5069. @c GET-CALLBACK
  5070. @page
  5071. @node get-callback, , defcallback, Callbacks
  5072. @heading get-callback
  5073. @subheading Syntax
  5074. @Accessor{get-callback symbol @res{} pointer}
  5075. @subheading Arguments and Values
  5076. @table @var
  5077. @item symbol
  5078. A symbol denoting a callback.
  5079. @item pointer
  5080. A pointer.
  5081. @end table
  5082. @subheading Description
  5083. This is the functional version of the @code{callback} macro. It
  5084. returns a pointer to the callback named by @var{symbol} suitable, for
  5085. example, to pass as arguments to foreign functions.
  5086. @subheading Examples
  5087. @lisp
  5088. CFFI> (defcallback sum :int ((a :int) (b :int))
  5089. (+ a b))
  5090. @result{} SUM
  5091. CFFI> (get-callback 'sum)
  5092. @result{} #<A Mac Pointer #x102350>
  5093. @end lisp
  5094. @subheading See Also
  5095. @seealso{callback} @*
  5096. @seealso{defcallback}
  5097. @c ===================================================================
  5098. @c CHAPTER: The Groveller
  5099. @node The Groveller, Limitations, Callbacks, Top
  5100. @chapter The Groveller
  5101. @cffi{}-Grovel is a tool which makes it easier to write @cffi{}
  5102. declarations for libraries that are implemented in C. That is, it
  5103. grovels through the system headers, getting information about types
  5104. and structures, so you don't have to. This is especially important
  5105. for libraries which are implemented in different ways by different
  5106. vendors, such as the @sc{unix}/@sc{posix} functions. The @cffi{}
  5107. declarations are usually quite different from platform to platform,
  5108. but the information you give to @cffi{}-Grovel is the same. Hence,
  5109. much less work is required!
  5110. If you use @acronym{ASDF}, @cffi{}-Grovel is integrated, so that it
  5111. will run automatically when your system is building. This feature was
  5112. inspired by SB-Grovel, a similar @acronym{SBCL}-specific project.
  5113. @cffi{}-Grovel can also be used without @acronym{ASDF}.
  5114. @section Building FFIs with CFFI-Grovel
  5115. @cffi{}-Grovel uses a specification file (*.lisp) describing the
  5116. features that need groveling. The C compiler is used to retrieve this
  5117. data and write a Lisp file (*.cffi.lisp) which contains the necessary
  5118. @cffi{} definitions to access the variables, structures, constants, and
  5119. enums mentioned in the specification.
  5120. @c This is most similar to the SB-Grovel package, upon which it is
  5121. @c based. Unlike SB-Grovel, we do not currently support defining
  5122. @c regular foreign functions in the specification file; those are best
  5123. @c defined in normal Lisp code.
  5124. @cffi{}-Grovel provides an @acronym{ASDF} component for handling the
  5125. necessary calls to the C compiler and resulting file management.
  5126. @c See the included CFFI-Unix package for an example of how to
  5127. @c integrate a specification file with ASDF-built packages.
  5128. @menu
  5129. * Groveller Syntax:: How grovel files should look like.
  5130. * Groveller ASDF Integration:: ASDF components for grovel files.
  5131. * Groveller Implementation Notes:: Implementation notes.
  5132. * Wrapper for Inline/Static Functions and Macros:: Wrapper
  5133. @end menu
  5134. @node Groveller Syntax, Groveller ASDF Integration, The Groveller, The Groveller
  5135. @section Specification File Syntax
  5136. The specification files are read by the normal Lisp reader, so they
  5137. have syntax very similar to normal Lisp code. In particular,
  5138. semicolon-comments and reader-macros will work as expected.
  5139. There are several forms recognized by @cffi{}-Grovel:
  5140. @deffn {Grovel Form} progn &rest forms
  5141. Processes a list of forms. Useful for conditionalizing several
  5142. forms. For example:
  5143. @end deffn
  5144. @lisp
  5145. #+freebsd
  5146. (progn
  5147. (constant (ev-enable "EV_ENABLE"))
  5148. (constant (ev-disable "EV_DISABLE")))
  5149. @end lisp
  5150. @deffn {Grovel Form} include &rest files
  5151. Include the specified files (specified as strings) in the generated C
  5152. source code.
  5153. @end deffn
  5154. @deffn {Grovel Form} in-package symbol
  5155. Set the package to be used for the final Lisp output.
  5156. @end deffn
  5157. @deffn {Grovel Form} ctype lisp-name size-designator
  5158. Define a @cffi{} foreign type for the string in @var{size-designator},
  5159. e.g. @code{(ctype :pid "pid_t")}.
  5160. @end deffn
  5161. @deffn {Grovel Form} constant (lisp-name &rest c-names) &key type documentation optional
  5162. Search for the constant named by the first @var{c-name} string found
  5163. to be known to the C preprocessor and define it as @var{lisp-name}.
  5164. The @var{type} keyword argument specifies how to grovel the constant:
  5165. either @code{integer} (the default) or @code{double-float}. If
  5166. @var{optional} is true, no error will be raised if all the
  5167. @var{c-names} are unknown. If @var{lisp-name} is a keyword, the actual
  5168. constant will be a symbol of the same name interned in the current
  5169. package.
  5170. @end deffn
  5171. @deffn {Grovel Form} feature lisp-feature-name c-name &key feature-list
  5172. Adds @var{lisp-feature-name} to the list @var{feature-list} if the @var{c-name}
  5173. string is known to the C preprocessor. @var{feature-list} defaults
  5174. to @code{cl:*features*}.
  5175. @end deffn
  5176. @deffn {Grovel Form} define name &optional value
  5177. Defines an additional C preprocessor symbol, which is useful for
  5178. altering the behavior of included system headers.
  5179. @end deffn
  5180. @deffn {Grovel Form} cc-flags &rest flags
  5181. Adds @var{cc-flags} to the command line arguments used for the C compiler
  5182. invocation.
  5183. @end deffn
  5184. @deffn {Grovel Form} pkg-config-cflags pkg &key optional
  5185. Adds @var{pkg} to the command line arguments for the external program
  5186. @code{pkg-config} and runs it to retrieve the relevant include flags
  5187. used for the C compiler invocation. This syntax can be used instead of
  5188. hard-coding paths using @code{cc-flags}, and ensures that include
  5189. flags are added correctly on the build system. Assumes
  5190. @code{pkg-config} is installed and working. @var{pkg} is a string
  5191. that identifies an installed @code{pkg-config} package. See the
  5192. pkg-config manual for more information. If @var{optional} is true,
  5193. failure to execute @code{pkg-config} does @emph{not} abort
  5194. compilation.
  5195. @end deffn
  5196. @deffn {Grovel Form} cstruct lisp-name c-name slots
  5197. Define a @cffi{} foreign struct with the slot data specfied. Slots
  5198. are of the form @code{(lisp-name c-name &key type count (signed t))}.
  5199. @end deffn
  5200. @deffn {Grovel Form} cunion lisp-name c-name slots
  5201. Identical to @code{cstruct}, but defines a @cffi{} foreign union.
  5202. @end deffn
  5203. @deffn {Grovel Form} cstruct-and-class c-name slots
  5204. Defines a @cffi{} foreign struct, as with @code{cstruct} and defines a
  5205. @acronym{CLOS} class to be used with it. This is useful for mapping
  5206. foreign structures to application-layer code that shouldn't need to
  5207. worry about memory allocation issues.
  5208. @end deffn
  5209. @deffn {Grovel Form} cvar namespec type &key read-only
  5210. Defines a foreign variable of the specified type, even if that
  5211. variable is potentially a C preprocessor pseudo-variable. e.g.
  5212. @code{(cvar ("errno" errno) errno-values)}, assuming that errno-values
  5213. is an enum or equivalent to type @code{:int}.
  5214. The @var{namespec} is similar to the one used in @ref{defcvar}.
  5215. @end deffn
  5216. @deffn {Grovel Form} cenum name-and-opts &rest elements
  5217. Defines a true C enum, with elements specified as @code{((lisp-name
  5218. &rest c-names) &key optional documentation)}.
  5219. @var{name-and-opts} can be either a symbol as name, or a list
  5220. @code{(name &key base-type define-constants)}. If @var{define-constants}
  5221. is non-null, a Lisp constant will be defined for each enum member.
  5222. @end deffn
  5223. @deffn {Grovel Form} constantenum name-and-opts &rest elements
  5224. Defines an enumeration of pre-processor constants, with elements
  5225. specified as @code{((lisp-name &rest c-names) &key optional
  5226. documentation)}.
  5227. @var{name-and-opts} can be either a symbol as name, or a list
  5228. @code{(name &key base-type define-constants)}. If @var{define-constants}
  5229. is non-null, a Lisp constant will be defined for each enum member.
  5230. This example defines @code{:af-inet} to represent the value held by
  5231. @code{AF_INET} or @code{PF_INET}, whichever the pre-processor finds
  5232. first. Similarly for @code{:af-packet}, but no error will be
  5233. signalled if the platform supports neither @code{AF_PACKET} nor
  5234. @code{PF_PACKET}.
  5235. @end deffn
  5236. @lisp
  5237. (constantenum address-family
  5238. ((:af-inet "AF_INET" "PF_INET")
  5239. :documentation "IPv4 Protocol family")
  5240. ((:af-local "AF_UNIX" "AF_LOCAL" "PF_UNIX" "PF_LOCAL")
  5241. :documentation "File domain sockets")
  5242. ((:af-inet6 "AF_INET6" "PF_INET6")
  5243. :documentation "IPv6 Protocol family")
  5244. ((:af-packet "AF_PACKET" "PF_PACKET")
  5245. :documentation "Raw packet access"
  5246. :optional t))
  5247. @end lisp
  5248. @deffn {Grovel Form} bitfield name-and-opts &rest elements
  5249. Defines a bitfield, with elements specified as @code{((lisp-name &rest
  5250. c-names) &key optional documentation)}. @var{name-and-opts} can be either a
  5251. symbol as name, or a list @code{(name &key base-type)}. For example:
  5252. @end deffn
  5253. @lisp
  5254. (bitfield flags-ctype
  5255. ((:flag-a "FLAG_A")
  5256. :documentation "DOCU_A")
  5257. ((:flag-b "FLAG_B" "FLAG_B_ALT")
  5258. :documentation "DOCU_B")
  5259. ((:flag-c "FLAG_C")
  5260. :documentation "DOCU_C"
  5261. :optional t))
  5262. @end lisp
  5263. @c ===================================================================
  5264. @c SECTION: Groveller ASDF Integration
  5265. @node Groveller ASDF Integration, Groveller Implementation Notes, Groveller Syntax, The Groveller
  5266. @section ASDF Integration
  5267. An example software project might contain four files; an
  5268. @acronym{ASDF} file, a package definition file, an implementation
  5269. file, and a @cffi{}-Grovel specification file.
  5270. The @acronym{ASDF} file defines the system and its dependencies.
  5271. Notice the use of @code{eval-when} to ensure @cffi{}-Grovel is present
  5272. and the use of @code{(cffi-grovel:grovel-file name &key cc-flags)}
  5273. instead of @code{(:file name)}.
  5274. The @file{example-software.asd} file would look like that:
  5275. @lisp
  5276. ;;; @lispcmt{CFFI-Grovel is needed for processing grovel-file components}
  5277. (defsystem "example-software"
  5278. :defsystem-depends-on ("cffi-grovel")
  5279. :depends-on ("cffi")
  5280. :serial t
  5281. :components
  5282. ((:file "package")
  5283. (:cffi-grovel-file "example-grovelling")
  5284. (:cffi-wrapper-file "example-wrappers")
  5285. (:file "example")))
  5286. @end lisp
  5287. The @file{package.lisp} file would contain one or several
  5288. @code{defpackage} forms, to remove circular dependencies and make
  5289. building the project easier. Note that you may or may not want to
  5290. @code{:use} your internal package.
  5291. @impnote{Note that it's a not a good idea to @code{:use} when names may
  5292. clash with, say, CL symbols.
  5293. Or you could use @code{uiop:define-package} and its @code{:mix} option.}
  5294. @lisp
  5295. (defpackage #:example-internal
  5296. (:use)
  5297. (:nicknames #:exampleint))
  5298. (defpackage #:example-software
  5299. (:export ...)
  5300. (:use #:cl #:cffi #:exampleint))
  5301. @end lisp
  5302. The internal package is created by Lisp code output from the C program
  5303. written by @cffi{}-Grovel; if your specification file is
  5304. @file{exampleint.lisp}, the @file{exampleint.cffi.lisp} file will contain the
  5305. @cffi{} definitions needed by the rest of your project.
  5306. @xref{Groveller Syntax}.
  5307. @node Groveller Implementation Notes, Wrapper for Inline/Static Functions and Macros, Groveller ASDF Integration, The Groveller
  5308. @section Implementation Notes
  5309. @cffi{}-Grovel will generate many files that not only architecture-specific,
  5310. but also implementation-specific, and should not be distributed.
  5311. ASDF will generate these files in its output cache;
  5312. if you build with multiple architectures (e.g. with NFS/AFS home
  5313. directories) or implementations, it is critical for avoiding clashes
  5314. to keep this cache in an implementation-dependent directory (as is the
  5315. default).
  5316. For @code{foo-internal.lisp}, the resulting @code{foo-internal.c},
  5317. @code{foo-internal}, and @code{foo-internal.cffi.lisp} are all
  5318. platform-specific, either because of possible reader-macros in
  5319. foo-internal.lisp, or because of varying C environments on the host
  5320. system. For this reason, it is not helpful to distribute any of those
  5321. files; end users building @cffi{}-Grovel based software will need
  5322. @code{cffi}-Grovel anyway.
  5323. @impnote{For now, after some experimentation with @sc{clisp} having no
  5324. long-long, it seems appropriate to assert that the generated @code{.c}
  5325. files are architecture and operating-system dependent, but
  5326. lisp-implementation independent. This way the same @code{.c} file
  5327. (and so the same @code{.grovel-tmp.lisp} file) will be shareable
  5328. between the implementations running on a given system.}
  5329. @c TODO: document the new wrapper stuff.
  5330. @node Wrapper for Inline/Static Functions and Macros, , Groveller Implementation Notes, The Groveller
  5331. @section Wrapper for Inline/Static Functions and Macros
  5332. In a shared library, information in static/inlined functions and
  5333. macros are already removed during the compilation. Wrapper file
  5334. enables to write an uninlined function wrapping the call to them.
  5335. A wrapper file compilation/loading proceeds as follows:
  5336. Unlike groveller which generates C code that emits lisp files
  5337. containing cffi definitions, it generates C code, compiles it as a
  5338. shared library, loads the library, generate the cffi definitions (as
  5339. lisp code) and then loads the lisp code.
  5340. It has asdf integration similar to groveller.
  5341. @lisp
  5342. (defsystem "example-software"
  5343. :defsystem-depends-on ("cffi-grovel")
  5344. :depends-on ("cffi")
  5345. :serial t
  5346. :components
  5347. ((:file "package")
  5348. (:cffi-grovel-file "example-grovelling")
  5349. (:cffi-wrapper-file "example-wrappers") ;; <<--- this part
  5350. (:file "example")))
  5351. @end lisp
  5352. @deffn {Wrapper Form} defwrapper name-and-options return-type &rest args
  5353. @end deffn
  5354. @example
  5355. static inline int foo(int i) @{
  5356. return 1+i;
  5357. @};
  5358. #define bar(i) (1+(i))
  5359. @end example
  5360. @lisp
  5361. (in-package :mypackage)
  5362. (defwrapper ("foo" foo) :int
  5363. (i :int))
  5364. (defwrapper ("bar" bar) :int
  5365. (i :int))
  5366. @end lisp
  5367. Other forms are similar to grovel files.
  5368. @deffn {Wrapper Form} progn &rest forms
  5369. Processes a list of forms. Useful for conditionalizing several
  5370. forms. For example:
  5371. @end deffn
  5372. @lisp
  5373. #+freebsd
  5374. (progn
  5375. (constant (ev-enable "EV_ENABLE"))
  5376. (constant (ev-disable "EV_DISABLE")))
  5377. @end lisp
  5378. @deffn {Wrapper Form} include &rest files
  5379. Include the specified files (specified as strings) in the generated C
  5380. source code.
  5381. @end deffn
  5382. @deffn {Wrapper Form} in-package symbol
  5383. Set the package to be used for the final Lisp output.
  5384. @end deffn
  5385. @deffn {Wrapper Form} flags &rest flags
  5386. Adds @var{cc-flags} to the command line arguments used for the C compiler
  5387. invocation.
  5388. @end deffn
  5389. @deffn {Wrapper Form} proclaim &rest proclaimations
  5390. @end deffn
  5391. @deffn {Wrapper Form} declaim &rest declaimations
  5392. @end deffn
  5393. @c ===================================================================
  5394. @c CHAPTER: Static Linking
  5395. @node Static Linking, Limitations, The Groveller, Top
  5396. @chapter Static Linking
  5397. On recent enough versions of supported implementations (currently, GNU
  5398. CLISP 2.49 or later, CMUCL 2015-11 or later, and SBCL 1.2.17 or later,
  5399. except SBCL 2.0.4), and with a recent enough ASDF (3.1.2 or later),
  5400. you can create a statically linked Lisp executable image (or a
  5401. standalone application executable) that includes all the C extensions
  5402. defined via @ref{The Groveller}'s @code{:cffi-wrapper-file} ASDF
  5403. components (and any other such objects output by
  5404. @code{asdf:compile-op}), as well as those defined by @code{:c-file} or
  5405. @code{:o-file} ASDF components, and your Lisp code. This makes it
  5406. easier to deliver your code as a single file.
  5407. Note that the resulting binary will typically still depend on any
  5408. shared libraries loaded via @xref{load-foreign-library} or
  5409. @xref{use-foreign-library} as well as core libraries such as
  5410. @code{libc}.
  5411. To dump a statically linked executable image, use:
  5412. @lisp
  5413. (asdf:load-system :cffi-grovel)
  5414. (asdf:operate :static-image-op :example-software)
  5415. @end lisp
  5416. To dump a statically linked executable standalone application, use:
  5417. @lisp
  5418. (asdf:load-system :cffi-grovel)
  5419. (asdf:operate :static-program-op :example-software)
  5420. @end lisp
  5421. See @uref{https://common-lisp.net/project/asdf/,,the ASDF
  5422. manual} for documentation about @code{image-op} and @code{program-op}
  5423. which are the parent operation classes that behave similarly except
  5424. they don't statically link C code.
  5425. @impnote{There is also an operation @code{:static-runtime-op} to create the
  5426. statically linked runtime alone, but it's admittedly not very useful
  5427. except as an intermediate step dependency towards building
  5428. @code{:static-image-op} or @code{:static-program-op}.}
  5429. @c ===================================================================
  5430. @c CHAPTER: Limitations
  5431. @node Limitations, Platform-specific features, The Groveller, Top
  5432. @chapter Limitations
  5433. These are @cffi{}'s limitations across all platforms; for information
  5434. on the warts on particular Lisp implementations, see
  5435. @ref{Implementation Support}.
  5436. @itemize @bullet
  5437. @item
  5438. The tutorial includes a treatment of the primary, intractable
  5439. limitation of @cffi{}, or any @acronym{FFI}: that the abstractions
  5440. commonly used by C are insufficiently expressive.
  5441. @xref{Tutorial-Abstraction,, Breaking the abstraction}, for more
  5442. details.
  5443. @end itemize
  5444. @node Platform-specific features, Glossary, Limitations, Top
  5445. @appendix Platform-specific features
  5446. Whenever a backend doesn't support one of @cffi{}'s features, a
  5447. specific symbol is pushed onto @code{common-lisp:*features*}. The
  5448. meanings of these symbols follow.
  5449. @table @var
  5450. @item cffi-sys::flat-namespace
  5451. This Lisp has a flat namespace for foreign symbols meaning that you
  5452. won't be able to load two different libraries with homograph functions
  5453. and successfully differentiate them through the @code{:library}
  5454. option to @code{defcfun}, @code{defcvar}, etc@dots{}
  5455. @item cffi-sys::no-foreign-funcall
  5456. The macro @code{foreign-funcall} is @strong{not} available. On such
  5457. platforms, the only way to call a foreign function is through
  5458. @code{defcfun}. @xref{foreign-funcall}, and @ref{defcfun}.
  5459. @item cffi-sys::no-long-long
  5460. The C @code{long long} type is @strong{not} available as a foreign
  5461. type.
  5462. However, on such platforms @cffi{} provides its own implementation of
  5463. the @code{long long} type for all of operations in chapters
  5464. @ref{Foreign Types}, @ref{Pointers} and @ref{Variables}. The
  5465. functionality described in @ref{Functions} and @ref{Callbacks} will
  5466. not be available.
  5467. 32-bit Lispworks 5.0+ is an exception. In addition to the @cffi{}
  5468. implementation described above, Lispworks itself implements the
  5469. @code{long long} type for @ref{Functions}. @ref{Callbacks} are still
  5470. missing @code{long long} support, though.
  5471. @item cffi-sys::no-stdcall
  5472. This Lisp doesn't support the @code{stdcall} calling convention. Note
  5473. that it only makes sense to support @code{stdcall} on (32-bit) x86
  5474. platforms.
  5475. @end table
  5476. @node Glossary, Comprehensive Index, Platform-specific features, Top
  5477. @appendix Glossary
  5478. @table @dfn
  5479. @item aggregate type
  5480. A @cffi{} type for C data defined as an organization of data of simple
  5481. type; in structures and unions, which are themselves aggregate types,
  5482. they are represented by value.
  5483. @item foreign value
  5484. This has two meanings; in any context, only one makes sense.
  5485. When using type translators, the foreign value is the lower-level Lisp
  5486. value derived from the object passed to @code{translate-to-foreign}
  5487. (@pxref{translate-to-foreign}). This value should be a Lisp number or
  5488. a pointer (satisfies @code{pointerp}), and it can be treated like any
  5489. general Lisp object; it only completes the transformation to a true
  5490. foreign value when passed through low-level code in the Lisp
  5491. implementation, such as the foreign function caller or indirect memory
  5492. addressing combined with a data move.
  5493. In other contexts, this refers to a value accessible by C, but which
  5494. may only be accessed through @cffi{} functions. The closest you can
  5495. get to such a foreign value is through a pointer Lisp object, which
  5496. itself counts as a foreign value in only the previous sense.
  5497. @item simple type
  5498. A @cffi{} type that is ultimately represented as a builtin type;
  5499. @cffi{} only provides extra semantics for Lisp that are invisible to C
  5500. code or data.
  5501. @end table
  5502. @node Comprehensive Index, , Glossary, Top
  5503. @unnumbered Index
  5504. @printindex cp
  5505. @bye