1C-Cookbook(3)         User Contributed Perl Documentation        C-Cookbook(3)
2
3
4

NAME

6       Inline::C-Cookbook - A Cornucopia of Inline C Recipes
7

DESCRIPTION

9       It's a lot easier for most of us to cook a meal from a recipe, rather
10       than just throwing things into a pot until something edible forms. So
11       it is with programming as well. "Inline.pm" makes C programming for
12       Perl as easy as possible. Having a set of easy to understand samples,
13       makes it simpler yet.
14
15       This Cookbook is intended to be an evergrowing repository of small yet
16       complete coding examples; each showing how to accomplish a particular
17       task with Inline. Each example is followed by a short discussion,
18       explaining in detail the particular features that are being
19       demonstrated.
20
21       Many of these recipes are apdapted from email discussions I have had
22       with Inline users around the world. It has been my experience so far,
23       that Inline provides an elegant solution to almost all problems
24       involving Perl and C.
25
26       Bon Appetit!
27

Appetizers

29   Hello, world
30       Problem
31           It seems that the first thing any programmer wants to do when he
32           learns a new programming technique is to use it to greet the Earth.
33           How can I do this using Inline?
34
35       Solution
36               use Inline C => <<'END_C';
37
38               void greet() {
39                   printf("Hello, world\n");
40               }
41               END_C
42
43               greet;
44
45       Discussion
46           Nothing too fancy here. We define a single C function "greet()"
47           which prints a message to STDOUT. One thing to note is that since
48           the Inline code comes before the function call to "greet", we can
49           call it as a bareword (no parentheses).
50
51       See Also
52           See Inline and Inline::C for basic info about "Inline.pm".
53
54       Credits
55           Brian Kernigan
56
57           Dennis Ritchie
58
59   One Liner
60       Problem
61           A concept is valid in Perl only if it can be shown to work in one
62           line.  Can Inline reduce the complexities of Perl/C interaction to
63           a one-liner?
64
65       Solution
66               perl -e 'use Inline C=>q{void greet(){printf("Hello, world\n");}};greet'
67
68       Discussion
69           Try doing that in XS :-)
70
71       See Also
72           My email signature of late is:
73
74               perl -le 'use Inline C=>q{SV*JAxH(char*x){return newSVpvf("Just Another %s Hacker",x);}};print JAxH+Perl'
75
76           A bit fancier but a few bytes too long to qualify as a true one
77           liner :-(
78
79       Credits
80           "Eli the Bearded" <elijah@workspot.net> gave me the idea that I
81           should have an Inline one-liner as a signature.
82

Meat & Potatoes

84   Data Types
85       Problem
86           How do I pass different types of data to and from Inline C
87           functions; like strings, numbers and integers?
88
89       Solution
90               # vowels.pl
91               use Inline C;
92
93               $filename = $ARGV[0];
94               die "Usage: perl vowels.pl filename\n" unless -f $filename;
95
96               $text = join '', <>;           # slurp input file
97               $vp = vowel_scan($text);       # call our function
98               $vp = sprintf("%03.1f", $vp * 100);  # format for printing
99               print "The letters in $filename are $vp% vowels.\n";
100
101               __END__
102               __C__
103
104               /* Find percentage of vowels to letters */
105               double vowel_scan(char* str) {
106                   int letters = 0;
107                   int vowels = 0;
108                   int i = 0;
109                   char c;
110                   char normalize = 'a' ^ 'A';
111                   /* normalize forces lower case in ASCII; upper in EBCDIC */
112                   char A = normalize | 'a';
113                   char E = normalize | 'e';
114                   char I = normalize | 'i';
115                   char O = normalize | 'o';
116                   char U = normalize | 'u';
117                   char Z = normalize | 'z';
118
119                   while(c = str[i++]) {
120                       c |= normalize;
121                       if (c >= A && c <= Z) {
122                            letters++;
123                            if (c == A || c == E || c == I || c == O || c == U)
124                                vowels++;
125                       }
126                   }
127
128                   return letters ? ((double) vowels / letters) : 0.0;
129               }
130
131       Discussion
132           This script takes a file name from the command line and prints the
133           ratio of vowels to letters in that file. "vowels.pl" uses an Inline
134           C function called "vowel_scan", that takes a string argument, and
135           returns the percentage of vowels as a floating point number between
136           0 and 1. It handles upper and lower case letters, and works with
137           ASCII and EBCDIC.  It is also quite fast.
138
139           Running this script produces:
140
141               > perl vowels.pl /usr/dict/words
142               The letters in /usr/dict/words are 37.5% vowels.
143
144       See Also
145           The Perl Journal vol #19 has an article about Inline which uses
146           this example.
147
148       Credits
149           This example was reprinted by permission of The Perl Journal. It
150           was edited to work with Inline v0.30 and higher.
151
152   Variable Argument Lists
153       Problem
154           How do I pass a variable-sized list of arguments to an Inline C
155           function?
156
157       Solution
158               greet(qw(Sarathy Jan Sparky Murray Mike));
159
160               use Inline C => <<'END_OF_C_CODE';
161
162               void greet(SV* name1, ...) {
163                   Inline_Stack_Vars;
164                   int i;
165
166                   for (i = 0; i < Inline_Stack_Items; i++)
167                       printf("Hello %s!\n", SvPV(Inline_Stack_Item(i), PL_na));
168
169                   Inline_Stack_Void;
170               }
171
172               END_OF_C_CODE
173
174       Discussion
175           This little program greets a group of people, such as my coworkers.
176           We use the "C" ellipsis syntax: ""..."", since the list can be of
177           any size.
178
179           Since there are no types or names associated with each argument, we
180           can't expect XS to handle the conversions for us. We'll need to pop
181           them off the Stack ourselves. Luckily there are two functions
182           (macros) that make this a very easy task.
183
184           First, we need to begin our function with a ""Inline_Stack_Vars""
185           statement. This defines a few internal variables that we need to
186           access the Stack. Now we can use ""Inline_Stack_Items"", which
187           returns an integer containing the number of arguments passed to us
188           from Perl.
189
190           NOTE: It is important to only use ""Inline_Stack_"" macros when
191           there is an ellipsis ("...") in the argument list, or the function
192           has a return type of void.
193
194           Second, we use the Inline_Stack_Item(x) function to access each
195           argument where "0 <= x < items".
196
197           NOTE: When using a variable length argument list, you have to
198           specify at least one argument before the ellipsis. (On my compiler,
199           anyway.) When XS does it's argument checking, it will complain if
200           you pass in less than the number of defined arguments. Therefore,
201           there is currently no way to pass an empty list when a variable
202           length list is expected.
203
204       See Also
205       Credits
206
207   Multiple Return Values
208       Problem
209           How do I return a list of values from a C function?
210
211       Solution
212               print map {"$_\n"} get_localtime(time);
213
214               use Inline C => <<'END_OF_C_CODE';
215
216               #include <time.h>
217
218               void get_localtime(int utc) {
219                 struct tm *ltime = localtime(&utc);
220                 Inline_Stack_Vars;
221
222                 Inline_Stack_Reset;
223                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_year)));
224                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_mon)));
225                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_mday)));
226                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_hour)));
227                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_min)));
228                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_sec)));
229                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_isdst)));
230                 Inline_Stack_Done;
231               }
232               END_OF_C_CODE
233
234       Discussion
235           Perl is a language where it is common to return a list of values
236           from a subroutine call instead of just a single value. C is not
237           such a language. In order to accomplish this in C we need to
238           manipulate the Perl call stack by hand. Luckily, Inline provides
239           macros to make this easy.
240
241           This example calls the system "localtime", and returns each of the
242           parts of the time struct; much like the perl builtin "localtime()".
243           On each stack push, we are creating a new Perl integer (SVIV) and
244           mortalizing it. The sv_2mortal() call makes sure that the reference
245           count is set properly. Without it, the program would leak memory.
246
247           NOTE: The "#include" statement is not really needed, because Inline
248           automatically includes the Perl headers which include almost all
249           standard system calls.
250
251       See Also
252           For more information on the Inline stack macros, see Inline::C.
253
254       Credits
255           Richard Anderson <starfire@zipcon.net> contributed the original
256           idea for this snippet.
257
258   Multiple Return Values (Another Way)
259       Problem
260           How can I pass back more than one value without using the Perl
261           Stack?
262
263       Solution
264               use Inline::Files;
265               use Inline C;
266
267               my ($foo, $bar);
268               change($foo, $bar);
269
270               print "\$foo = $foo\n";
271               print "\$bar = $bar\n";
272
273               __C__
274
275               int change(SV* var1, SV* var2) {
276                   sv_setpvn(var1, "Perl Rocks!", 11);
277                   sv_setpvn(var2, "Inline Rules!", 13);
278                   return 1;
279               }
280
281       Discussion
282           Most perl function interfaces return values as a list of one or
283           more scalars. Very few like "chomp", will modify an input scalar in
284           place.  On the other hand, in C you do this quite often. Values are
285           passed in by reference and modified in place by the called
286           function.
287
288           It turns out that we can do that with Inline as well. The secret is
289           to use a type of '"SV*"' for each argument that is to be modified.
290           This ensures passing by reference, because no typemapping is
291           needed.
292
293           The function can then use the Perl5 API to operate on that
294           argument.  When control returns to Perl, the argument will retain
295           the value set by the C function. In this example we passed in 2
296           empty scalars and assigned values directly to them.
297
298       See Also
299       Credits
300           Ned Konz <ned@bike-nomad.com> brought this behavior to my
301           attention. He also pointed out that he is not the world famous
302           computer cyclist Steve Roberts (http://www.microship.com), but he
303           is close (http://bike-nomad.com). Thanks Ned.
304
305   Using Memory
306       Problem
307           How should I allocate buffers in my Inline C code?
308
309       Solution
310               print greeting('Ingy');
311
312               use Inline C => <<'END_OF_C_CODE';
313
314               SV* greeting(SV* sv_name) {
315                   return (newSVpvf("Hello %s!\n", SvPV(sv_name, PL_na)));
316               }
317
318               END_OF_C_CODE
319
320       Discussion
321           In this example we will return the greeting to the caller, rather
322           than printing it. This would seem mighty easy, except for the fact
323           that we need to allocate a small buffer to create the greeting.
324
325           I would urge you to stay away from "malloc"ing your own buffer.
326           Just use Perl's built in memory management. In other words, just
327           create a new Perl string scalar. The function "newSVpv" does just
328           that. And "newSVpvf" includes "sprintf" functionality.
329
330           The other problem is getting rid of this new scalar. How will the
331           ref count get decremented after we pass the scalar back? Perl also
332           provides a function called "sv_2mortal". Mortal variables die when
333           the context goes out of scope. In other words, Perl will wait until
334           the new scalar gets passed back and then decrement the ref count
335           for you, thereby making it eligible for garbage collection. See
336           "perldoc perlguts".
337
338           In this example the "sv_2mortal" call gets done under the hood by
339           XS, because we declared the return type to be "SV*".
340
341           To view the generated XS code, run the command ""perl
342           -MInline=INFO,FORCE,NOCLEAN example004.pl"". This will leave the
343           build directory intact and tell you where to find it.
344
345       See Also
346       Credits
347

Fast Food

349   Inline CGI
350       Problem
351           How do I use Inline securely in a CGI environment?
352
353       Solution
354               #!/usr/bin/perl
355
356               use CGI qw(:standard);
357               use Inline (Config =>
358                           DIRECTORY => '/usr/local/apache/Inline',
359                          );
360
361               print (header,
362                      start_html('Inline CGI Example'),
363                      h1(JAxH('Inline')),
364                      end_html
365                     );
366
367               use Inline C => <<END;
368               SV* JAxH(char* x) {
369                   return newSVpvf("Just Another %s Hacker", x);
370               }
371               END
372
373       Discussion
374           The problem with running Inline code from a CGI script is that
375           Inline writes to a build area on your disk whenever it compiles
376           code. Most CGI scripts don't (and shouldn't) be able to create a
377           directory and write into it.
378
379           The solution is to explicitly tell Inline which directory to use
380           with the 'use Inline Config => DIRECTORY => ...' line. Then you
381           need to give write access to that directory from the web server
382           (CGI script).
383
384           If you see this as a security hole, then there is another option.
385           Give write access to yourself, but read-only access to the CGI
386           script. Then run the script once by hand (from the command line).
387           This will cause Inline to precompile the C code. That way the CGI
388           will only need read access to the build directory (to load in the
389           shared library from there).
390
391           Just remember that whenever you change the C code, you need to
392           precompile it again.
393
394       See Also
395           See CGI for more information on using the "CGI.pm" module.
396
397       Credits
398
399   mod_perl
400       Problem
401           How do I use Inline with mod_perl?
402
403       Solution
404               package Factorial;
405               use strict;
406               use Inline Config =>
407                          DIRECTORY => '/usr/local/apache/Inline',
408                          ENABLE => 'UNTAINT';
409               use Inline 'C';
410               Inline->init;
411
412               sub handler {
413                   my $r = shift;
414                   $r->send_http_header('text/plain');
415                   printf "%3d! = %10d\n", $_, factorial($_) for 1..100;
416                   return Apache::Constants::OK;
417               }
418
419               1;
420               __DATA__
421               __C__
422               double factorial(double x) {
423                   if (x < 2)  return 1;
424                   return x * factorial(x - 1)
425               }
426
427       Discussion
428           This is a fully functional mod_perl handler that prints out the
429           factorial values for the numbers 1 to 100. Since we are using
430           Inline under mod_perl, there are a few considerations to , um,
431           consider.
432
433           First, mod_perl handlers are usually run with "-T" taint detection.
434           Therefore, we need to enable the UNTAINT option. The next thing to
435           deal with is the fact that this handler will most likely be loaded
436           after Perl's compile time. Since we are using the DATA section, we
437           need to use the special "init()" call. And of course we need to
438           specify a DIRECTORY that mod_perl can compile into. See the above
439           CGI example for more info.
440
441           Other than that, this is a pretty straightforward mod_perl handler,
442           tuned for even more speed!
443
444       See Also
445           See Stas Bekman's upcoming O'Reilly book on mod_perl to which this
446           example was contributed.
447
448       Credits
449
450   Object Oriented Inline
451       Problem
452           How do I implement Object Oriented programming in Perl using C
453           objects?
454
455       Solution
456               my $obj1 = Soldier->new('Benjamin', 'Private', 11111);
457               my $obj2 = Soldier->new('Sanders', 'Colonel', 22222);
458               my $obj3 = Soldier->new('Matt', 'Sergeant', 33333);
459
460               for my $obj ($obj1, $obj2, $obj3) {
461                   print  $obj->get_serial, ") ",
462                          $obj->get_name, " is a ",
463                          $obj->get_rank, "\n";
464               }
465
466               #---------------------------------------------------------
467
468               package Soldier;
469
470               use Inline C => <<'END';
471
472               typedef struct {
473                 char* name;
474                 char* rank;
475                 long  serial;
476                 } Soldier;
477
478
479
480               SV* new(char* class, char* name, char* rank, long serial) {
481                   Soldier* soldier;
482                   SV*      obj_ref = newSViv(0);
483                   SV*      obj = newSVrv(obj_ref, class);
484
485                   New(42, soldier, 1, Soldier);
486
487                   soldier->name = savepv(name);
488                   soldier->rank = savepv(rank);
489                   soldier->serial = serial;
490
491                   sv_setiv(obj, (IV)soldier);
492                   SvREADONLY_on(obj);
493                   return obj_ref;
494                }
495
496                char* get_name(SV* obj) {
497                      return ((Soldier*)SvIV(SvRV(obj)))->name;
498                }
499
500                char* get_rank(SV* obj) {
501                      return ((Soldier*)SvIV(SvRV(obj)))->rank;
502                }
503
504                long get_serial(SV* obj) {
505                     return ((Soldier*)SvIV(SvRV(obj)))->serial;
506                }
507
508                void DESTROY(SV* obj) {
509                     Soldier* soldier = (Soldier*)SvIV(SvRV(obj));
510                     Safefree(soldier->name);
511                     Safefree(soldier->rank);
512                     Safefree(soldier);
513               }
514
515               END
516
517       Discussion
518           Damian Conway has given us myriad ways of implementing OOP in Perl.
519           This is one he might not have thought of.
520
521           The interesting thing about this example is that it uses Perl for
522           all the OO bindings while using C for the attributes and methods.
523
524           If you examine the Perl code everything looks exactly like a
525           regular OO example. There is a "new" method and several accessor
526           methods. The familiar 'arrow syntax' is used to invoke them.
527
528           In the class definition (second part) the Perl "package" statement
529           is used to name the object class or namespace. But that's where the
530           similarities end Inline takes over.
531
532           The idea is that we call a C subroutine called "new()" which
533           returns a blessed scalar. The scalar contains a readonly integer
534           which is a C pointer to a Soldier struct. This is our object.
535
536           The "new()" function needs to malloc the memory for the struct and
537           then copy the initial values into it using "savepv()". This also
538           allocates more memory (which we have to keep track of).
539
540           Note that "newSVrv()" doesn't create a reference, but returns a new
541           SV ('obj') and makes 'obj_ref' a reference to it. Ultimately,
542           'obj_ref' (which is the SV that "new()" returns) holds a reference
543           to the blessed scalar in 'obj', which in turn contains an integer
544           that corresponds to the memory address of the C object.
545
546           The accessor methods are pretty straightforward. They return the
547           current value of their attribute.
548
549           The last method "DESTROY()" is called automatically by Perl
550           whenever an object goes out of scope. This is where we can free all
551           the memory used by the object.
552
553           That's it. It's a very simplistic example. It doesn't show off any
554           advanced OO features, but it is pretty cool to see how easy the
555           implementation can be. The important Perl call is "newSVrv()" which
556           creates a blessed scalar.
557
558       See Also
559           Read "Object Oriented Perl" by Damian Conway, for more useful ways
560           of doing OOP in Perl.
561
562           You can learn more Perl calls in perlapi. If you don't have Perl
563           5.6.0 or higher, visit
564           http://www.perldoc.com/perl5.6/pod/perlapi.html
565
566       Credits
567

The Main Course

569   Exposing Shared Libraries
570       Problem
571           You have this great C library and you want to be able to access
572           parts of it with Perl.
573
574       Solution
575               print get('http://www.axkit.org');
576
577               use Inline C => Config =>
578                          LIBS => '-lghttp';
579               use Inline C => <<'END_OF_C_CODE';
580
581               #include <ghttp.h>
582
583               char *get(SV* uri) {
584                  SV* buffer;
585                  ghttp_request* request;
586
587                  buffer = NEWSV(0,0);
588                  request = ghttp_request_new();
589                  ghttp_set_uri(request, SvPV(uri, PL_na));
590
591                  ghttp_set_header(request, http_hdr_Connection, "close");
592
593                  ghttp_prepare(request);
594                  ghttp_process(request);
595
596                  sv_catpv(buffer, ghttp_get_body(request));
597
598                  ghttp_request_destroy(request);
599
600                  return SvPV(buffer, PL_na);
601               }
602
603               END_OF_C_CODE
604
605       Discussion
606           This example fetches and prints the HTML from http://www.axkit.org
607           It requires the GNOME http libraries. http://www.gnome.org
608
609           One of the most common questions I get is "How can I use Inline to
610           make use of some shared library?". Although it has always been
611           possible to do so, the configuration was ugly, and there were no
612           specific examples.
613
614           With version 0.30 and higher, you can specify the use of shared
615           libraries easily with something like this:
616
617               use Inline C => Config => LIBS => '-lghttp';
618               use Inline C => "code ...";
619
620           or
621
622               use Inline C => "code ...", LIBS => '-lghttp';
623
624           To specify a specific library path, use:
625
626               use Inline C => "code ...", LIBS => '-L/your/lib/path -lyourlib';
627
628           To specify an include path use:
629
630               use Inline C => "code ...",
631                          LIBS => '-lghttp',
632                          INC => '-I/your/inc/path';
633
634       See Also
635           The "LIBS" and "INC" configuration options are formatted and passed
636           into MakeMaker. For more info see ExtUtils::MakeMaker. For more
637           options see Inline::C.
638
639       Credits
640           This code was written by Matt Sergeant <matt@sergeant.org>, author
641           of many CPAN modules. The configuration syntax has been modified
642           for use with Inline v0.30.
643
644   Automatic Function Wrappers
645       Problem
646           You have some functions in a C library that you want to access from
647           Perl exactly as you would from C.
648
649       Solution
650           The error function "erf()" is probably defined in your standard
651           math library. Annoyingly, Perl does not let you access it. To print
652           out a small table of its values, just say:
653
654               perl -le 'use Inline C => q{ double erf(double); }, ENABLE => "AUTOWRAP"; print "$_ @{[erf($_)]}" for (0..10)'
655
656           The excellent "Term::ReadLine::Gnu" implements Term::ReadLine using
657           the GNU ReadLine library. Here is an easy way to access just
658           "readline()" from that library:
659
660               package MyTerm;
661
662               use Inline C => Config =>
663                          ENABLE => AUTOWRAP =>
664                          LIBS => "-lreadline -lncurses -lterminfo -ltermcap ";
665               use Inline C => q{ char * readline(char *); };
666
667               package main;
668               my $x = MyTerm::readline("xyz: ");
669
670           Note however that it fails to "free()" the memory returned by
671           readline, and that "Term::ReadLine::Gnu" offers a much richer
672           interface.
673
674       Discussion
675           We access existing functions by merely showing Inline their
676           declarations, rather than a full definition. Of course the function
677           declared must exist, either in a library already linked to Perl or
678           in a library specified using the "LIBS" option.
679
680           The first example wraps a function from the standard math library,
681           so Inline requires no additional "LIBS" directive. The second uses
682           the Config option to specify the libraries that contain the actual
683           compiled C code.
684
685           This behavior is always disabled by default. You must enable the
686           "AUTOWRAP" option to make it work.
687
688       See Also
689           "readline", "Term::ReadLine::Gnu"
690
691       Credits
692           GNU ReadLine was written by Brian Fox <bfox@ai.mit.edu> and Chet
693           Ramey <chet@ins.cwru.edu>. Term::ReadLine::Gnu was written by Hiroo
694           Hayashi <hiroo.hayashi@computer.org>. Both are far richer than the
695           slim interface given here!
696
697           The idea of producing wrapper code given only a function
698           declaration is taken from Swig by David M. Beazley
699           <beazley@cs.uchicago.edu>.
700
701           Ingy's inline editorial insight:
702
703           This entire entry was contributed by Ariel Scolnicov
704           <ariels@compugen.co.il>. Ariel also first suggested the idea for
705           Inline to support function declaration processing.
706
707   Complex Data
708       Problem
709           How do I deal with complex data types like hashes in Inline C?
710
711       Solution
712               use Inline C => <<'END_OF_C_CODE';
713
714               void dump_hash(SV* hash_ref) {
715                   HV* hash;
716                   HE* hash_entry;
717                   int num_keys, i;
718                   SV* sv_key;
719                   SV* sv_val;
720
721                   if (! SvROK(hash_ref))
722                       croak("hash_ref is not a reference");
723
724                   hash = (HV*)SvRV(hash_ref);
725                   num_keys = hv_iterinit(hash);
726                   for (i = 0; i < num_keys; i++) {
727                       hash_entry = hv_iternext(hash);
728                       sv_key = hv_iterkeysv(hash_entry);
729                       sv_val = hv_iterval(hash, hash_entry);
730                       printf("%s => %s\n", SvPV(sv_key, PL_na), SvPV(sv_val, PL_na));
731                   }
732                   return;
733               }
734
735               END_OF_C_CODE
736
737               my %hash = (
738                           Author => "Brian Ingerson",
739                           Nickname => "INGY",
740                           Module => "Inline.pm",
741                           Version => "0.30",
742                           Language => "C",
743                          );
744
745               dump_hash(\%hash);
746
747       Discussion
748           The world is not made of scalars alone, although they are
749           definitely the easiest creatures to deal with, when doing Inline
750           stuff.  Sometimes we need to deal with arrays, hashes, and code
751           references, among other things.
752
753           Since Perl subroutine calls only pass scalars as arguments, we'll
754           need to use the argument type "SV*" and pass references to more
755           complex types.
756
757           The above program dumps the key/value pairs of a hash. To figure it
758           out, just curl up with perlapi for a couple hours. Actually, its
759           fairly straight forward once you are familiar with the calls.
760
761           Note the "croak" function call. This is the proper way to die from
762           your C extensions.
763
764       See Also
765           See perlapi for information about the Perl5 internal API.
766
767       Credits
768
769   Hash of Lists
770       Problem
771           How do I create a Hash of Lists from C?
772
773       Solution
774               use Inline C;
775               use Data::Dumper;
776
777               $hash_ref = load_data("./cartoon.txt");
778               print Dumper $hash_ref;
779
780               __END__
781               __C__
782
783               static int next_word(char**, char*);
784
785               SV* load_data(char* file_name) {
786                   char buffer[100], word[100], * pos;
787                   AV* array;
788                   HV* hash = newHV();
789                   FILE* fh = fopen(file_name, "r");
790
791                   while (fgets(pos = buffer, sizeof(buffer), fh)) {
792                       if (next_word(&pos, word)) {
793                           hv_store(hash, word, strlen(word),
794                                   newRV_noinc((SV*)array = newAV()), 0);
795                           while (next_word(&pos, word))
796                               av_push(array, newSVpvf("%s", word));
797                       }
798                   }
799                   fclose(fh);
800                   return newRV_noinc((SV*) hash);
801               }
802
803               static int next_word(char** text_ptr, char* word) {
804                   char* text = *text_ptr;
805                   while(*text != '\0' &&
806                         *text <= ' ')
807                       text++;
808                   if (*text <= ' ')
809                       return 0;
810                   while(*text != '\0' &&
811                         *text > ' ') {
812                       *word++ = *text++;
813                   }
814                   *word = '\0';
815                   *text_ptr = text;
816                   return 1;
817               }
818
819       Discussion
820           This is one of the larger recipes. But when you consider the number
821           of calories it has, it's not so bad. The function "load_data" takes
822           the name of a file as it's input. The file "cartoon.text" might
823           look like:
824
825               flintstones fred barney
826               jetsons     george jane elroy
827               simpsons    homer marge bart
828
829           The function will read the file, parsing each line into words. Then
830           it will create a new hash, whereby the first word in a line becomes
831           a hash key and the remaining words are put into an array whose
832           reference becomes the hash value. The output looks like this:
833
834               $VAR1 = {
835                         'flintstones' => [
836                                            'fred',
837                                            'barney'
838                                          ],
839                         'simpsons' => [
840                                         'homer',
841                                         'marge',
842                                         'bart'
843                                       ],
844                         'jetsons' => [
845                                        'george',
846                                        'jane',
847                                        'elroy'
848                                      ]
849                       };
850
851       See Also
852           See perlapi for information about the Perl5 internal API.
853
854       Credits
855           Al Danial <alnd@pacbell.net> requested a solution to this on
856           comp.lang.perl.misc. He borrowed the idea from the "Hash of Lists"
857           example in the Camel book.
858

Just Desserts

860   Win32
861       Problem
862           How do I access Win32 DLL-s using Inline?
863
864       Solution
865               use Inline C => DATA =>
866                          LIBS => '-luser32';
867
868               $text = "@ARGV" || 'Inline.pm works with MSWin32. Scary...';
869
870               WinBox('Inline Text Box', $text);
871
872               __END__
873               __C__
874
875               #include <windows.h>
876
877               int WinBox(char* Caption, char* Text) {
878                 return MessageBoxA(0, Text, Caption, 0);
879               }
880
881       Discussion
882           This example runs on MS Windows. It makes a text box appear on the
883           screen which contains a message of your choice.
884
885           The important thing is that its proof that you can use Inline to
886           interact with Windows DLL-s. Very scary indeed. 8-o
887
888           To use Inline on Windows with ActivePerl (
889           http://www.ActiveState.com ) you'll need MS Visual Studio. You can
890           also use the Cygwin environment, available at http://www.cygwin.com
891           .
892
893       See Also
894           See Inline-Support for more info on MSWin32 programming with
895           Inline.
896
897       Credits
898           This example was adapted from some sample code written by Garrett
899           Goebel <garrett@scriptpro.com>
900
901   Embedding Perl in C
902       Problem
903           How do I use Perl from a regular C program?
904
905       Solution
906               #!/usr/bin/cpr
907
908               int main(void) {
909
910                   printf("Using Perl version %s from a C program!\n\n",
911                          CPR_eval("use Config; $Config{version};"));
912
913                   CPR_eval("use Data::Dumper;");
914                   CPR_eval("print Dumper \\%INC;");
915
916                   return 0;
917
918               }
919
920       Discussion
921           By using CPR. (C Perl Run)
922
923           This example uses another Inline module, "Inline::CPR", available
924           separately on CPAN. When you install this module it also installs a
925           binary interpreter called "/usr/bin/cpr". (The path may be
926           different on your system)
927
928           When you feed a C program to the CPR interpreter, it automatically
929           compiles and runs your code using Inline. This gives you full
930           access to the Perl internals. CPR also provides a set of easy to
931           use C macros for calling Perl internals.
932
933           This means that you can effectively "run" C source code by putting
934           a CPR hashbang as the first line of your C program.
935
936       See Also
937           See Inline::CPR for more information on using CPR.
938
939           "Inline::CPR" can be obtained from
940           http://search.cpan.org/search?dist=Inline-CPR
941
942       Credits
943           Randal Schwartz <merlyn@stonehenge.com>, Randolph Bentson
944           <bentson@grieg.holmsjoen.com>, Richard Anderson
945           <starfire@zipcon.net>, and Tim Maher <tim@consultix-inc.com> helped
946           me figure out how to write a program that would work as a hashbang.
947

Entertaining Guests

949       As of version 0.30, Inline has the ability to work in cooperation with
950       other modules that want to expose a C API of their own. The general
951       syntax for doing this is:
952
953           use Inline with => 'Module';
954           use Inline C => ... ;
955
956       This tells "Module" to pass configuration options to Inline. Options
957       like typemaps, include paths, and external libraries, are all resolved
958       automatically so you can just concentrate on writing the functions.
959
960   Event handling with Event.pm
961       Problem
962           You need to write a C callback for the "Event.pm" module. Can this
963           be done more easily with Inline?
964
965       Solution
966               use Inline with => 'Event';
967
968               Event->timer(desc     => 'Timer #1',
969                            interval => 2,
970                            cb       => \&my_callback,
971                           );
972
973               Event->timer(desc     => 'Timer #2',
974                            interval => 3,
975                            cb       => \&my_callback,
976                           );
977
978               print "Starting...\n";
979               Event::loop;
980
981               use Inline C => <<'END';
982               void my_callback(pe_event* event) {
983                   pe_timer * watcher = event->up;
984
985                   printf("%s\n\tEvent priority = %d\n\tWatcher priority = %d\n\n",
986                          SvPVX(watcher->base.desc),
987                          event->prio,
988                          watcher->base.prio
989                         );
990               }
991               END
992
993       Discussion
994           The first line tells Inline to load the "Event.pm" module. Inline
995           then queries "Event" for configuration information. It gets the
996           name and location of Event's header files, typemaps and shared
997           objects. The parameters that "Event" returns look like:
998
999               INC => "-I $path/Event",
1000               TYPEMAPS => "$path/Event/typemap",
1001               MYEXTLIB => "$path/auto/Event/Event.$so",
1002               AUTO_INCLUDE => '#include "EventAPI.h"',
1003               BOOT => 'I_EVENT_API("Inline");',
1004
1005           Doing all of this automatically allows you, the programmer, to
1006           simply write a function that receives a pointer of type
1007           'pe_event*'. This gives you access to the "Event" structure that
1008           was passed to you.
1009
1010           In this example, I simply print values out of the structure. The
1011           Perl code defines 2 timer events which each invoke the same
1012           callback. The first one, every two seconds, and the second one,
1013           every three seconds.
1014
1015           As of this writing, "Event.pm" is the only CPAN module that works
1016           in cooperation with Inline.
1017
1018       See Also
1019           Read the "Event.pm" documentation for more information. It contains
1020           a tutorial showing several examples of using Inline with "Event".
1021
1022       Credits
1023           Jochen Stenzel <perl@jochen-stenzel.de> originally came up with the
1024           idea of mixing Inline and "Event". He also authored the "Event"
1025           tutorial.
1026
1027           Joshua Pritikin <joshua.pritikin@db.com> is the author of
1028           "Event.pm".
1029

Food for Thought

1031   Calling C from both Perl and C
1032       Problem
1033           I'd like to be able to call the same C function from both Perl and
1034           C.  Also I like to define a C function that doesn't get bound to
1035           Perl.  How do I do that?
1036
1037       Solution
1038               print "9 + 5 = ", add(9, 5), "\n";
1039               print "SQRT(9^2 + 5^2) = ", pyth(9, 5), "\n";
1040               print "9 * 5 = ", mult(9, 5), "\n";
1041
1042               use Inline C => <<'END_C';
1043               int add(int x, int y) {
1044                   return x + y;
1045               }
1046               static int mult(int x, int y) {
1047                   return x * y;
1048               }
1049               double pyth(int x, int y) {
1050                   return sqrt(add(mult(x, x), mult(y, y)));
1051               }
1052               END_C
1053
1054       Discussion
1055           The program produces:
1056
1057               9 + 5 = 14
1058               SQRT(9^2 + 5^2) = 10.295630140987
1059               Can't locate auto/main/mult.al in @INC ...
1060
1061           Every Inline function that is bound to Perl is also callable by C.
1062           You don't have to do anything special. Inline arranges it so that
1063           all the typemap code gets done by XS and is out of sight. By the
1064           time the C function receives control, everything has been converted
1065           from Perl to C.
1066
1067           Of course if your function manipulates the Perl Stack, you probably
1068           don't want to call it from C (unless you really know what you're
1069           doing).
1070
1071           If you declare a function as "static", Inline won't bind it to
1072           Perl.  That's why we were able to call "mult()" from C but the call
1073           failed from Perl.
1074
1075       See Also
1076       Credits
1077
1078   Calling Perl from C
1079       Problem
1080           So now that I can call C from Perl, how do I call a Perl subroutine
1081           from an Inline C function.
1082
1083       Solution
1084               use Inline C;
1085
1086               for(1..5) {
1087                  c_func_1('This is the first line');
1088                  c_func_2('This is the second line');
1089                  print "\n";
1090               }
1091
1092               sub perl_sub_1 {
1093                   print map "$_\n", @_;
1094               }
1095
1096               __DATA__
1097               __C__
1098
1099               void c_func_2(SV* text) {
1100                    dSP;
1101
1102                    ENTER;
1103                    SAVETMPS;
1104
1105                    XPUSHs(sv_2mortal(newSVpvf("Plus an extra line")));
1106                    PUTBACK;
1107
1108                    call_pv("perl_sub_1", G_DISCARD);
1109
1110                    FREETMPS;
1111                    LEAVE;
1112               }
1113
1114               void c_func_1(SV* text) {
1115                    c_func_2(text);
1116               }
1117
1118       Discussion
1119           This demo previously made use of Inline Stack macros only - but
1120           that's not the correct way to do it. Instead, base the callbacks on
1121           the perlcall documentation (as we're now doing).
1122
1123           Actually, this program demonstrates calling a C function which
1124           calls another C function which in turn calls a Perl subroutine.
1125
1126           The nice thing about Inline C functions is that you can call them
1127           from both Perl-space and C-space. That's because Inline creates a
1128           wrapper function around each C function. When you use Perl to call
1129           C you're actually calling that function's wrapper. The wrapper
1130           handles typemapping and Stack management, and then calls your C
1131           function.
1132
1133           The first time we call "c_func_1" which calls "c_func_2". The
1134           second time we call "c_func_2" directly. "c_func_2" calls the Perl
1135           subroutine ("perl_sub_1") using the internal "perl_call_pv"
1136           function. It has to put arguments on the stack by hand. Since there
1137           is already one argument on the stack when we enter the function,
1138           the "XPUSHs" ( which is equivalent to an "Inline_Stack_Push" ) adds
1139           a second argument.
1140
1141           We iterate through a 'for' loop 5 times just to demonstrate that
1142           things still work correctly when we do that. (This was where the
1143           previous rendition, making use solely of Inline Stack macros, fell
1144           down.)
1145
1146       See Also
1147           See Inline::C for more information about Stack macros.
1148
1149           See perlapi for more information about the Perl5 internal API.
1150
1151       Credits
1152
1153   Evaling C
1154       Problem
1155           I've totally lost my marbles and I want to generate C code at run
1156           time, and "eval" it into Perl. How do I do this?
1157
1158       Solution
1159               use Inline;
1160               use Code::Generator;
1161
1162               my $c_code = generate('foo_function');
1163
1164               Inline->bind(C => $c_code);
1165
1166               foo_function(1, 2, 3);
1167
1168       Discussion
1169           I can't think of a real life application where you would want to
1170           generate C code on the fly, but at least I know how I would do it.
1171           :)
1172
1173           The "bind()" function of Inline let's you bind
1174           (compile/load/execute) C functions at run time. It takes all of the
1175           same arguments as 'use Inline C => ...'.
1176
1177           The nice thing is that once a particular snippet is compiled, it
1178           remains cached so that it doesn't need to be compiled again. I can
1179           imagine that someday a mad scientist will dream up a self
1180           generating modeling system that would run faster and faster over
1181           time.
1182
1183           If you know such a person, have them drop me a line.
1184
1185       See Also
1186       Credits
1187
1188   Providing a pure perl alternative
1189       Problem
1190           I want to write a script that will use a C subroutine if Inline::C
1191           is installed, but will otherwise use an equivalent pure perl
1192           subroutine if Inline::C is not already installed.  How do I do
1193           this?
1194
1195       Solution
1196             use strict;
1197              use warnings;
1198
1199             eval {
1200              require Inline;
1201              Inline->import (C => Config =>
1202                              BUILD_NOISY => 1);
1203              Inline->import (C =><<'EOC');
1204
1205              int foo() {
1206                warn("Using Inline\n");
1207                return 42;
1208              }
1209
1210             EOC
1211             };
1212
1213             if($@) {
1214               *foo =\&bar;
1215             }
1216
1217             sub bar {
1218               warn("Using Pure Perl Implementation\n");
1219               return 42;
1220             }
1221
1222             my $x = foo();
1223             print "$x\n";
1224
1225       Discussion
1226           If Inline::C is installed and functioning properly, the C sub foo
1227           is called by the perl code. Otherwise, $@ gets set, and the
1228           equivalent pure perl function bar is instead called.
1229
1230           Note, too, that the pure perl sub bar can still be explicitly
1231           called even if Inline::C is available.
1232
1233   Accessing Fortran subs using Inline::C
1234       Problem
1235           I've been given a neat little sub written in fortran that takes, as
1236           its args, two integers and returns their product. And I would like
1237           to use that sub as is from Inline::C. By way of example, let's say
1238           that the fortran source file is named 'prod.f', and that it looks
1239           like this:
1240
1241                 integer function sqarea(r,s)
1242                 integer r, s
1243                 sqarea = r*s
1244                 return
1245                 end
1246
1247       Solution
1248           We can't access that code directly, but we can compile it into a
1249           library which we *can* then access from Inline::C.  Using gcc we
1250           could run:
1251
1252             gfortran -c prod.f -o prod.o
1253             ar cru libprod.a prod.o
1254
1255           The function is then accessible as follows:
1256
1257             use warnings;
1258
1259             use Inline C => Config =>
1260               LIBS =>
1261                '-L/full/path/to/libprod_location -lprod -lgfortran';
1262
1263             use Inline C => <<'  EOC';
1264
1265             int wrap_sqarea(int a, int b) {
1266                 return sqarea_(&a, &b);
1267             }
1268
1269             EOC
1270
1271             $x = 15;
1272             $y = $x + 3;
1273             $ret = wrap_sqarea($x, $y);
1274             print "Product of $x and $y is $ret\n";
1275
1276       Discussion
1277           Note firstly that, although the function is specified as 'sqarea'
1278           in the source file, gfortran appends an underscore to the name when
1279           the source is compiled. (I don't know if *all* fortran compilers do
1280           this.) Therefore Inline::C needs to call the function as 'sqarea_'.
1281
1282           Secondly, because fortran subs pass args by reference, we need to
1283           pass the *addresses* of the two integer args to sqarea() when we
1284           call it from our Inline::C sub.
1285
1286           If using g77 instead of gfortran, the only necessary change is that
1287           we specify '-lg2c' instead of '-lgfortran' in our 'LIBS' setting.
1288

SEE ALSO

1290       For generic information about Inline, see Inline.
1291
1292       For information about using Inline with C see Inline::C.
1293
1294       For information on supported languages and platforms see Inline-
1295       Support.
1296
1297       For information on writing your own Inline language support module, see
1298       Inline-API.
1299
1300       Inline's mailing list is inline@perl.org
1301
1302       To subscribe, send email to inline-subscribe@perl.org
1303

AUTHOR

1305       Brian Ingerson <INGY@cpan.org>
1306
1308       Copyright (c) 2001, 2002. Brian Ingerson.
1309
1310       Copyright (c) 2008, 2010-2013. Sisyphus.
1311
1312       All Rights Reserved. This module is free software. It may be used,
1313       redistributed and/or modified under the terms of the Perl Artistic
1314       License.
1315
1316       See http://www.perl.com/perl/misc/Artistic.html
1317
1318
1319
1320perl v5.16.3                      2013-03-07                     C-Cookbook(3)
Impressum