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               use Inline C => <<'END';
469
470               typedef struct {
471                 char* name;
472                 char* rank;
473                 long  serial;
474                 } Soldier;
475
476
477
478               SV* new(char* class, char* name, char* rank, long serial) {
479                   Soldier* soldier;
480                   SV*      obj_ref = newSViv(0);
481                   SV*      obj = newSVrv(obj_ref, class);
482
483                   New(42, soldier, 1, Soldier);
484
485                   soldier->name = savepv(name);
486                   soldier->rank = savepv(rank);
487                   soldier->serial = serial;
488
489                   sv_setiv(obj, (IV)soldier);
490                   SvREADONLY_on(obj);
491                   return obj_ref;
492                }
493
494                char* get_name(SV* obj) {
495                      return ((Soldier*)SvIV(SvRV(obj)))->name;
496                }
497
498                char* get_rank(SV* obj) {
499                      return ((Soldier*)SvIV(SvRV(obj)))->rank;
500                }
501
502                long get_serial(SV* obj) {
503                     return ((Soldier*)SvIV(SvRV(obj)))->serial;
504                }
505
506                void DESTROY(SV* obj) {
507                     Soldier* soldier = (Soldier*)SvIV(SvRV(obj));
508                     Safefree(soldier->name);
509                     Safefree(soldier->rank);
510                     Safefree(soldier);
511               }
512
513               END
514
515       Discussion
516           Damian Conway has given us myriad ways of implementing OOP in Perl.
517           This is one he might not have thought of.
518
519           The interesting thing about this example is that it uses Perl for
520           all the OO bindings while using C for the attributes and methods.
521
522           If you examine the Perl code everything looks exactly like a
523           regular OO example. There is a "new" method and several accessor
524           methods. The familiar 'arrow syntax' is used to invoke them.
525
526           In the class definition (second part) the Perl "package" statement
527           is used to name the object class or namespace. But that's where the
528           similarities end Inline takes over.
529
530           The idea is that we call a C subroutine called "new()" which
531           returns a blessed scalar. The scalar contains a readonly integer
532           which is a C pointer to a Soldier struct. This is our object.
533
534           The "new()" function needs to malloc the memory for the struct and
535           then copy the initial values into it using "strdup()". This also
536           allocates more memory (which we have to keep track of).
537
538           The accessor methods are pretty straightforward. They return the
539           current value of their attribute.
540
541           The last method "DESTROY()" is called automatically by Perl
542           whenever an object goes out of scope. This is where we can free all
543           the memory used by the object.
544
545           That's it. It's a very simplistic example. It doesn't show off any
546           advanced OO features, but it is pretty cool to see how easy the
547           implementation can be. The important Perl call is "newSVrv()" which
548           creates a blessed scalar.
549
550       See Also
551           Read "Object Oriented Perl" by Damian Conway, for more useful ways
552           of doing OOP in Perl.
553
554           You can learn more Perl calls in perlapi. If you don't have Perl
555           5.6.0 or higher, visit
556           http://www.perldoc.com/perl5.6/pod/perlapi.html
557
558       Credits
559

The Main Course

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

Just Desserts

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

Entertaining Guests

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

Food for Thought

1023   Calling C from both Perl and C
1024       Problem
1025           I'd like to be able to call the same C function from both Perl and
1026           C.  Also I like to define a C function that doesn't get bound to
1027           Perl.  How do I do that?
1028
1029       Solution
1030               print "9 + 5 = ", add(9, 5), "\n";
1031               print "SQRT(9^2 + 5^2) = ", pyth(9, 5), "\n";
1032               print "9 * 5 = ", mult(9, 5), "\n";
1033
1034               use Inline C => <<'END_C';
1035               int add(int x, int y) {
1036                   return x + y;
1037               }
1038               static int mult(int x, int y) {
1039                   return x * y;
1040               }
1041               double pyth(int x, int y) {
1042                   return sqrt(add(mult(x, x), mult(y, y)));
1043               }
1044               END_C
1045
1046       Discussion
1047           The program produces:
1048
1049               9 + 5 = 14
1050               SQRT(9^2 + 5^2) = 10.295630140987
1051               Can't locate auto/main/mult.al in @INC ...
1052
1053           Every Inline function that is bound to Perl is also callable by C.
1054           You don't have to do anything special. Inline arranges it so that
1055           all the typemap code gets done by XS and is out of sight. By the
1056           time the C function receives control, everything has been converted
1057           from Perl to C.
1058
1059           Of course if your function manipulates the Perl Stack, you probably
1060           don't want to call it from C (unless you really know what you're
1061           doing).
1062
1063           If you declare a function as "static", Inline won't bind it to
1064           Perl.  That's why we were able to call "mult()" from C but the call
1065           failed from Perl.
1066
1067       See Also
1068       Credits
1069
1070   Calling Perl from C
1071       Problem
1072           So now that I can call C from Perl, how do I call a Perl subroutine
1073           from an Inline C function.
1074
1075       Solution
1076               use Inline C;
1077
1078               c_func_1('This is the first line');
1079               c_func_2('This is the second line');
1080
1081               sub perl_sub_1 {
1082                   print map "$_\n", @_;
1083               }
1084
1085               __DATA__
1086               __C__
1087
1088               void c_func_2(SV* text) {
1089                   Inline_Stack_Vars;
1090                   Inline_Stack_Push(newSVpvf("Plus an extra line"));
1091                   Inline_Stack_Done;
1092                   perl_call_pv("main::perl_sub_1", 0);
1093                   Inline_Stack_Void;
1094               }
1095
1096               void c_func_1(SV* text) {
1097                   c_func_2(text);
1098               }
1099
1100       Discussion
1101           Actually, this program demonstrates calling a C function which
1102           calls another C function which in turn calls a Perl subroutine.
1103
1104           The nice thing about Inline C functions is that you can call them
1105           from both Perl-space and C-space. That's because Inline creates a
1106           wrapper function around each C function. When you use Perl to call
1107           C you're actually calling that function's wrapper. The wrapper
1108           handles typemapping and Stack management, and then calls your C
1109           function.
1110
1111           The first time we call "c_func_1" which calls "c_func_2". The
1112           second time we call "c_func_2" directly. "c_func_2" calls the Perl
1113           subroutine ("perl_sub_1") using the internal "perl_call_pv"
1114           function. It has to put arguments on the stack by hand. Since there
1115           is already one argument on the stack when we enter the function,
1116           the "Inline_Stack_Push" adds a second argument. "Inline_Stack_Void"
1117           makes sure that nothing is returned from the function.
1118
1119       See Also
1120           See Inline::C for more information about Stack macros.
1121
1122           See perlapi for more information about the Perl5 internal API.
1123
1124       Credits
1125
1126   Evaling C
1127       Problem
1128           I've totally lost my marbles and I want to generate C code at run
1129           time, and "eval" it into Perl. How do I do this?
1130
1131       Solution
1132               use Inline;
1133               use Code::Generator;
1134
1135               my $c_code = generate('foo_function');
1136
1137               Inline->bind(C => $c_code);
1138
1139               foo_function(1, 2, 3);
1140
1141       Discussion
1142           I can't think of a real life application where you would want to
1143           generate C code on the fly, but at least I know how I would do it.
1144           :)
1145
1146           The "bind()" function of Inline let's you bind
1147           (compile/load/execute) C functions at run time. It takes all of the
1148           same arguments as 'use Inline C => ...'.
1149
1150           The nice thing is that once a particular snippet is compiled, it
1151           remains cached so that it doesn't need to be compiled again. I can
1152           imagine that someday a mad scientist will dream up a self
1153           generating modeling system that would run faster and faster over
1154           time.
1155
1156           If you know such a person, have them drop me a line.
1157
1158       See Also
1159       Credits
1160

SEE ALSO

1162       For generic information about Inline, see Inline.
1163
1164       For information about using Inline with C see Inline::C.
1165
1166       For information on supported languages and platforms see Inline-
1167       Support.
1168
1169       For information on writing your own Inline language support module, see
1170       Inline-API.
1171
1172       Inline's mailing list is inline@perl.org
1173
1174       To subscribe, send email to inline-subscribe@perl.org
1175

AUTHOR

1177       Brian Ingerson <INGY@cpan.org>
1178
1180       Copyright (c) 2001, 2002, Brian Ingerson.
1181
1182       All Rights Reserved. This module is free software. It may be used,
1183       redistributed and/or modified under the terms of the Perl Artistic
1184       License.
1185
1186       See http://www.perl.com/perl/misc/Artistic.html
1187
1188
1189
1190perl v5.12.1                      2010-01-28                     C-Cookbook(3)
Impressum