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

NAME

6       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 demon‐
19       strated.
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 involv‐
24       ing Perl and C.
25
26       Bon Appetit!
27

Appetizers

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

Meat & Potatoes

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

Fast Food

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

The Main Course

568       Exposing Shared Libraries
569
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 pos‐
611           sible to do so, the configuration was ugly, and there were no spe‐
612           cific 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
646       Problem
647           You have some functions in a C library that you want to access from
648           Perl exactly as you would from C.
649
650       Solution
651           The error function "erf()" is probably defined in your standard
652           math library. Annoyingly, Perl does not let you access it. To print
653           out a small table of its values, just say:
654
655               perl -le 'use Inline C => q{ double erf(double); }, ENABLE => "AUTOWRAP"; print "$_ @{[erf($_)]}" for (0..10)'
656
657           The excellent "Term::ReadLine::Gnu" implements Term::ReadLine using
658           the GNU ReadLine library. Here is an easy way to access just "read‐
659           line()" from that library:
660
661               package MyTerm;
662
663               use Inline C => Config =>
664                          ENABLE => AUTOWRAP =>
665                          LIBS => "-lreadline -lncurses -lterminfo -ltermcap ";
666               use Inline C => q{ char * readline(char *); };
667
668               package main;
669               my $x = MyTerm::readline("xyz: ");
670
671           Note however that it fails to "free()" the memory returned by read‐
672           line, and that "Term::ReadLine::Gnu" offers a much richer inter‐
673           face.
674
675       Discussion
676           We access existing functions by merely showing Inline their decla‐
677           rations, rather than a full definition. Of course the function
678           declared must exist, either in a library already linked to Perl or
679           in a library specified using the "LIBS" option.
680
681           The first example wraps a function from the standard math library,
682           so Inline requires no additional "LIBS" directive. The second uses
683           the Config option to specify the libraries that contain the actual
684           compiled C code.
685
686           This behavior is always disabled by default. You must enable the
687           "AUTOWRAP" option to make it work.
688
689       See Also
690           "readline", "Term::ReadLine::Gnu"
691
692       Credits
693           GNU ReadLine was written by Brian Fox <bfox@ai.mit.edu> and Chet
694           Ramey <chet@ins.cwru.edu>. Term::ReadLine::Gnu was written by Hiroo
695           Hayashi <hiroo.hayashi@computer.org>. Both are far richer than the
696           slim interface given here!
697
698           The idea of producing wrapper code given only a function declara‐
699           tion is taken from Swig by David M. Beazley <beaz‐
700           ley@cs.uchicago.edu>.
701
702           Ingy's inline editorial insight:
703
704           This entire entry was contributed by Ariel Scolnicov <ariels@compu‐
705           gen.co.il>. Ariel also first suggested the idea for Inline to sup‐
706           port function declaration processing.
707
708       Complex Data
709
710       Problem
711           How do I deal with complex data types like hashes in Inline C?
712
713       Solution
714               use Inline C => <<'END_OF_C_CODE';
715
716               void dump_hash(SV* hash_ref) {
717                   HV* hash;
718                   HE* hash_entry;
719                   int num_keys, i;
720                   SV* sv_key;
721                   SV* sv_val;
722
723                   if (! SvROK(hash_ref))
724                       croak("hash_ref is not a reference");
725
726                   hash = (HV*)SvRV(hash_ref);
727                   num_keys = hv_iterinit(hash);
728                   for (i = 0; i < num_keys; i++) {
729                       hash_entry = hv_iternext(hash);
730                       sv_key = hv_iterkeysv(hash_entry);
731                       sv_val = hv_iterval(hash, hash_entry);
732                       printf("%s => %s\n", SvPV(sv_key, PL_na), SvPV(sv_val, PL_na));
733                   }
734                   return;
735               }
736
737               END_OF_C_CODE
738
739               my %hash = (
740                           Author => "Brian Ingerson",
741                           Nickname => "INGY",
742                           Module => "Inline.pm",
743                           Version => "0.30",
744                           Language => "C",
745                          );
746
747               dump_hash(\%hash);
748
749       Discussion
750           The world is not made of scalars alone, although they are defi‐
751           nitely the easiest creatures to deal with, when doing Inline stuff.
752           Sometimes we need to deal with arrays, hashes, and code references,
753           among other things.
754
755           Since Perl subroutine calls only pass scalars as arguments, we'll
756           need to use the argument type "SV*" and pass references to more
757           complex types.
758
759           The above program dumps the key/value pairs of a hash. To figure it
760           out, just curl up with perlapi for a couple hours. Actually, its
761           fairly straight forward once you are familiar with the calls.
762
763           Note the "croak" function call. This is the proper way to die from
764           your C extensions.
765
766       See Also
767           See perlapi for information about the Perl5 internal API.
768
769       Credits
770
771       Hash of Lists
772
773       Problem
774           How do I create a Hash of Lists from C?
775
776       Solution
777               use Inline C;
778               use Data::Dumper;
779
780               $hash_ref = load_data("./cartoon.txt");
781               print Dumper $hash_ref;
782
783               __END__
784               __C__
785
786               static int next_word(char**, char*);
787
788               SV* load_data(char* file_name) {
789                   char buffer[100], word[100], * pos;
790                   AV* array;
791                   HV* hash = newHV();
792                   FILE* fh = fopen(file_name, "r");
793
794                   while (fgets(pos = buffer, sizeof(buffer), fh)) {
795                       if (next_word(&pos, word)) {
796                           hv_store(hash, word, strlen(word),
797                                   newRV_noinc((SV*)array = newAV()), 0);
798                           while (next_word(&pos, word))
799                               av_push(array, newSVpvf("%s", word));
800                       }
801                   }
802                   fclose(fh);
803                   return newRV_noinc((SV*) hash);
804               }
805
806               static int next_word(char** text_ptr, char* word) {
807                   char* text = *text_ptr;
808                   while(*text != '\0' &&
809                         *text <= ' ')
810                       text++;
811                   if (*text <= ' ')
812                       return 0;
813                   while(*text != '\0' &&
814                         *text > ' ') {
815                       *word++ = *text++;
816                   }
817                   *word = '\0';
818                   *text_ptr = text;
819                   return 1;
820               }
821
822       Discussion
823           This is one of the larger recipes. But when you consider the number
824           of calories it has, it's not so bad. The function "load_data" takes
825           the name of a file as it's input. The file "cartoon.text" might
826           look like:
827
828               flintstones fred barney
829               jetsons     george jane elroy
830               simpsons    homer marge bart
831
832           The function will read the file, parsing each line into words. Then
833           it will create a new hash, whereby the first word in a line becomes
834           a hash key and the remaining words are put into an array whose ref‐
835           erence becomes the hash value. The output looks like this:
836
837               $VAR1 = {
838                         'flintstones' => [
839                                            'fred',
840                                            'barney'
841                                          ],
842                         'simpsons' => [
843                                         'homer',
844                                         'marge',
845                                         'bart'
846                                       ],
847                         'jetsons' => [
848                                        'george',
849                                        'jane',
850                                        'elroy'
851                                      ]
852                       };
853
854       See Also
855           See perlapi for information about the Perl5 internal API.
856
857       Credits
858           Al Danial <alnd@pacbell.net> requested a solution to this on
859           comp.lang.perl.misc. He borrowed the idea from the "Hash of Lists"
860           example in the Camel book.
861

Just Desserts

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

Entertaining Guests

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

Food for Thought

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

SEE ALSO

1177       For generic information about Inline, see Inline.
1178
1179       For information about using Inline with C see Inline::C.
1180
1181       For information on supported languages and platforms see Inline-Sup‐
1182       port.
1183
1184       For information on writing your own Inline language support module, see
1185       Inline-API.
1186
1187       Inline's mailing list is inline@perl.org
1188
1189       To subscribe, send email to inline-subscribe@perl.org
1190

AUTHOR

1192       Brian Ingerson <INGY@cpan.org>
1193
1195       Copyright (c) 2001, 2002, Brian Ingerson.
1196
1197       All Rights Reserved. This module is free software. It may be used,
1198       redistributed and/or modified under the terms of the Perl Artistic
1199       License.
1200
1201       See http://www.perl.com/perl/misc/Artistic.html
1202
1203
1204
1205perl v5.8.8                       2002-11-04                     C-Cookbook(3)
Impressum