1Inline::C::Cookbook(3)User Contributed Perl DocumentationInline::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 adapted 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
32       It seems that the first thing any programmer wants to do when he learns
33       a new programming technique is to use it to greet the Earth. How can I
34       do this using Inline?
35
36       Solution
37               use Inline C => <<'...';
38
39               void greet() {
40                 printf("Hello, world\n");
41               }
42               ...
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       Problem
62           A concept is valid in Perl only if it can be shown to work in one
63           line. Can Inline reduce the complexities of Perl/C interaction to a
64           one-liner?
65
66       Solution
67               perl -e 'use Inline C=>q{void greet(){printf("Hello, world\n");}};greet'
68
69       Discussion
70           Try doing that in XS :-)
71
72       See Also
73           My email signature of late is:
74
75               perl -le 'use Inline C=>q{SV*JAxH(char*x){return newSVpvf("Just Another %s Hacker",x);}};print JAxH+Perl'
76
77           A bit fancier but a few bytes too long to qualify as a true one
78           liner :-(
79
80       Credits
81           "Eli the Bearded" <elijah@workspot.net> gave me the idea that I
82           should have an Inline one-liner as a signature.
83

MEAT & POTATOES

85   Data Types
86       Problem
87           How do I pass different types of data to and from Inline C
88           functions; like strings, numbers and integers?
89
90       Solution
91               # vowels.pl
92               use Inline 'C';
93
94               $filename = $ARGV[0];
95               die "Usage: perl vowels.pl filename\n" unless -f $filename;
96
97               $text = join '', <>;           # slurp input file
98               $vp = vowel_scan($text);       # call our function
99               $vp = sprintf("%03.1f", $vp * 100);  # format for printing
100               print "The letters in $filename are $vp% vowels.\n";
101
102               __END__
103               __C__
104
105               /* Find percentage of vowels to letters */
106               double vowel_scan(char* str) {
107                 int letters = 0;
108                 int vowels = 0;
109                 int i = 0;
110                 char c;
111                 char normalize = 'a' ^ 'A';
112                 /* normalize forces lower case in ASCII; upper in EBCDIC */
113                 char A = normalize | 'a';
114                 char E = normalize | 'e';
115                 char I = normalize | 'i';
116                 char O = normalize | 'o';
117                 char U = normalize | 'u';
118                 char Z = normalize | 'z';
119
120                 while(c = str[i++]) {
121                   c |= normalize;
122                   if (c >= A && c <= Z) {
123                      letters++;
124                      if (c == A || c == E || c == I || c == O || c == U)
125                        vowels++;
126                   }
127                 }
128
129                 return letters ? ((double) vowels / letters) : 0.0;
130               }
131
132       Discussion
133           This script takes a file name from the command line and prints the
134           ratio of vowels to letters in that file. "vowels.pl" uses an Inline
135           C function called "vowel_scan", that takes a string argument, and
136           returns the percentage of vowels as a floating point number between
137           0 and 1. It handles upper and lower case letters, and works with
138           ASCII and EBCDIC. It is also quite fast.
139
140           Running this script produces:
141
142               > perl vowels.pl /usr/dict/words
143               The letters in /usr/dict/words are 37.5% vowels.
144
145           It is very important to note that the examples in this cookbook use
146           "char *" to mean a string. Internally Perl has various mechanisms
147           to deal with strings that contain characters with code points above
148           255, using Unicode. This means that naively treating strings as
149           "char *", an array of 8-bit characters, can lead to problems. You
150           need to be aware of this and consider using a UTF-8 library to deal
151           with strings.
152
153       See Also
154           The Perl Journal vol #19 has an article about Inline which uses
155           this example.
156
157       Credits
158           This example was reprinted by permission of The Perl Journal. It
159           was edited to work with Inline v0.30 and higher.
160
161   Variable Argument Lists
162       Problem
163
164       How do I pass a variable-sized list of arguments to an Inline C
165       function?
166
167       Solution
168               greet(qw(Sarathy Jan Sparky Murray Mike));
169
170               use Inline C => <<'END_OF_C_CODE';
171
172               void greet(SV* name1, ...) {
173                 Inline_Stack_Vars;
174                 int i;
175
176                 for (i = 0; i < Inline_Stack_Items; i++)
177                   printf("Hello %s!\n", SvPV(Inline_Stack_Item(i), PL_na));
178
179                 Inline_Stack_Void;
180               }
181
182               END_OF_C_CODE
183
184       Discussion
185           This little program greets a group of people, such as my coworkers.
186           We use the "C" ellipsis syntax: ""..."", since the list can be of
187           any size.
188
189           Since there are no types or names associated with each argument, we
190           can't expect XS to handle the conversions for us. We'll need to pop
191           them off the Stack ourselves. Luckily there are two functions
192           (macros) that make this a very easy task.
193
194           First, we need to begin our function with a ""Inline_Stack_Vars""
195           statement.  This defines a few internal variables that we need to
196           access the Stack. Now we can use ""Inline_Stack_Items"", which
197           returns an integer containing the number of arguments passed to us
198           from Perl.
199
200           NOTE: It is important to only use ""Inline_Stack_"" macros when
201           there is an ellipsis ("...") in the argument list, or the function
202           has a return type of void.
203
204           Second, we use the Inline_Stack_Item(x) function to access each
205           argument where "0 <= x < items".
206
207           NOTE: When using a variable length argument list, you have to
208           specify at least one argument before the ellipsis. (On my compiler,
209           anyway.) When XS does it's argument checking, it will complain if
210           you pass in less than the number of defined arguments. Therefore,
211           there is currently no way to pass an empty list when a variable
212           length list is expected.
213
214       See Also
215       Credits
216
217   Multiple Return Values
218       Problem
219           How do I return a list of values from a C function?
220
221       Solution
222               print map {"$_\n"} get_localtime(time);
223
224               use Inline C => <<'END_OF_C_CODE';
225
226               #include <time.h>
227
228               void get_localtime(SV * utc) {
229                 const time_t utc_ = (time_t)SvIV(utc);
230                 struct tm *ltime = localtime(&utc_);
231                 Inline_Stack_Vars;
232
233                 Inline_Stack_Reset;
234                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_year)));
235                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_mon)));
236                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_mday)));
237                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_hour)));
238                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_min)));
239                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_sec)));
240                 Inline_Stack_Push(sv_2mortal(newSViv(ltime->tm_isdst)));
241                 Inline_Stack_Done;
242               }
243               END_OF_C_CODE
244
245       Discussion
246           Perl is a language where it is common to return a list of values
247           from a subroutine call instead of just a single value. C is not
248           such a language. In order to accomplish this in C we need to
249           manipulate the Perl call stack by hand. Luckily, Inline provides
250           macros to make this easy.
251
252           This example calls the system "localtime", and returns each of the
253           parts of the time struct; much like the perl builtin "localtime()".
254           On each stack push, we are creating a new Perl integer (SVIV) and
255           mortalizing it. The sv_2mortal() call makes sure that the reference
256           count is set properly. Without it, the program would leak memory.
257
258           NOTE: The "#include" statement is not really needed, because Inline
259                 automatically includes the Perl headers which include almost
260           all
261                 standard system calls.
262
263       See Also
264           For more information on the Inline stack macros, see Inline::C.
265
266       Credits
267           Richard Anderson <starfire@zipcon.net> contributed the original
268           idea for this snippet.
269
270   Multiple Return Values (Another Way)
271       Problem
272           How can I pass back more than one value without using the Perl
273           Stack?
274
275       Solution
276               use Inline::Files;
277               use Inline 'C';
278
279               my ($foo, $bar);
280               change($foo, $bar);
281
282               print "\$foo = $foo\n";
283               print "\$bar = $bar\n";
284
285               __C__
286
287               int change(SV* var1, SV* var2) {
288                 sv_setpvn(var1, "Perl Rocks!", 11);
289                 sv_setpvn(var2, "Inline Rules!", 13);
290                 return 1;
291               }
292
293       Discussion
294           Most perl function interfaces return values as a list of one or
295           more scalars.  Very few like "chomp", will modify an input scalar
296           in place. On the other hand, in C you do this quite often. Values
297           are passed in by reference and modified in place by the called
298           function.
299
300           It turns out that we can do that with Inline as well. The secret is
301           to use a type of '"SV*"' for each argument that is to be modified.
302           This ensures passing by reference, because no typemapping is
303           needed.
304
305           The function can then use the Perl5 API to operate on that
306           argument. When control returns to Perl, the argument will retain
307           the value set by the C function. In this example we passed in 2
308           empty scalars and assigned values directly to them.
309
310       See Also
311       Credits
312           Ned Konz <ned@bike-nomad.com> brought this behavior to my
313           attention. He also pointed out that he is not the world famous
314           computer cyclist Steve Roberts ( <http://www.microship.com> ), but
315           he is close ( <http://bike-nomad.com> ).  Thanks Ned.
316
317   Taking an array-ref as an argument
318       Problem
319           How can I take a Perl array-ref as an argument in my C function?
320
321       Solution
322               SV *sum(SV *array) {
323                   int total = 0;
324                   int numelts, i;
325                   if ((!SvROK(array))
326                       || (SvTYPE(SvRV(array)) != SVt_PVAV)
327                       || ((numelts = av_len((AV *)SvRV(array))) < 0)
328                   ) {
329                       return &PL_sv_undef;
330                   }
331                   for (i = 0; i <= numelts; i++) {
332                       total += SvIV(*av_fetch((AV *)SvRV(array), i, 0));
333                   }
334                   return newSViv(total);
335               }
336
337       Discussion
338           This example returns "undef" if given a non-ref, or a non-array-
339           ref, or a ref to an empty array. You can see how you might expand
340           this to take more than one array-ref.
341
342   Using Memory
343       Problem
344           How should I allocate buffers in my Inline C code?
345
346       Solution
347               print greeting('Ingy');
348
349               use Inline C => <<'END_OF_C_CODE';
350
351               SV* greeting(SV* sv_name) {
352                 return (newSVpvf("Hello %s!\n", SvPV(sv_name, PL_na)));
353               }
354
355               END_OF_C_CODE
356
357       Discussion
358           In this example we will return the greeting to the caller, rather
359           than printing it. This would seem mighty easy, except for the fact
360           that we need to allocate a small buffer to create the greeting.
361
362           I would urge you to stay away from "malloc"ing your own buffer.
363           Just use Perl's built in memory management. In other words, just
364           create a new Perl string scalar. The function "newSVpv" does just
365           that. And "newSVpvf" includes "sprintf" functionality.
366
367           The other problem is getting rid of this new scalar. How will the
368           ref count get decremented after we pass the scalar back? Perl also
369           provides a function called "sv_2mortal". Mortal variables die when
370           the context goes out of scope.  In other words, Perl will wait
371           until the new scalar gets passed back and then decrement the ref
372           count for you, thereby making it eligible for garbage collection.
373           See "perldoc perlguts".
374
375           In this example the "sv_2mortal" call gets done under the hood by
376           XS, because we declared the return type to be "SV*".
377
378           To view the generated XS code, run the command ""perl -
379           MInline=INFO,FORCE,NOCLEAN example004.pl"". This will leave the
380           build directory intact and tell you where to find it.
381
382       See Also
383       Credits
384
385   Direct Access to Perl variables
386       Problem
387           Can I write an Inline C function that can access a Perl variable
388           directly without having to pass it as an argument?
389
390       Solution
391               use strict;
392               use warnings;
393               use Inline C => "DATA";
394
395               our $mesh_data = "MESH-POINTS 0.0 0.0 0.5 0.25 1.0 0.5 1.5 0.75";
396               CalcSurfaceHeights();
397
398               __DATA__
399               __C__
400               #define N_MP 4
401
402               void CalcSurfaceHeights() {
403                  double x[N_MP], y[N_MP], z;
404                  int    ix;
405                  char   *mesh_data = SvPV_nolen(get_sv("main::mesh_data", 0));
406
407                  sscanf(mesh_data, "MESH-POINTS %lf%lf%lf%lf%lf%lf%lf%lf",
408                                    x, y, x+1, y+1, x+2, y+2, x+3, y+3);
409
410                  for (ix=0; ix < N_MP; ix++) {
411                     z = 0.5*( sin(x[ix]) + sin(y[ix]) );
412
413                     printf("Surface-Height: %6.3f Mesh-Point: %6.2f, %6.2f\n",
414                            z, x[ix], y[ix]);
415                  }
416               }
417
418       Discussion
419           There are really only two points that need an explanation to
420           understand why the above code works. In the Perl section, you will
421           notice the declaration
422
423               our $mesh_data = "...";
424
425           For Perl variables to be directly accessible from Inline::C
426           functions, they must be declared as package variables. Lexical
427           variables, those declared with my, cannot be accessed this way.
428
429           In the C code section of the example, the following line is what
430           makes direct access to the Perl variable work;
431
432               char *mesh_data = SvPV_nolen(get_sv("main::mesh_data", 0))
433
434           Here SvPV_nolen() returns a pointer to the C string contained in
435           the scalar variable. The "_nolen" variation ignores the length of
436           the C string. Hence, the function takes only a single argument,
437           which is the SV* of the scalar variable.
438
439           We could have used the usual two-argument form of SvPV() and, since
440           we don't care about the string length, specified PL_na for the
441           second argument. The function call would then change to,
442
443               SvPV(get_sv("main::mesh_data", 0), PL_na)
444
445           The function get_sv() returns the SV* of a named scalar package
446           variable.  It takes a C string, containing the fully qualified name
447           of the variable, as the first argument. The second argument
448           contains flag values related to data type. Since we are only
449           reading the scalar variable, in our example, a value of 0 can be
450           used.
451
452       See Also
453           ·   perldoc perlguts
454
455           ·   perldoc perlapi
456
457       Credits
458           The code example and description were inspired by a discussion
459           thread on the Inline mailing list (inline@perl.org).
460

FAST FOOD

462   Inline CGI
463       Problem
464           How do I use Inline securely in a CGI environment?
465
466       Solution
467               #!/usr/bin/perl
468
469               use CGI qw(:standard);
470               use Inline Config =>
471                 DIRECTORY => '/usr/local/apache/Inline';
472
473               print
474                 header,
475                 start_html('Inline CGI Example'),
476                 h1(JAxH('Inline')),
477                 end_html;
478
479               use Inline C => <<END;
480               SV* JAxH(char* x) {
481                 return newSVpvf("Just Another %s Hacker", x);
482               }
483               END
484
485       Discussion
486           The problem with running Inline code from a CGI script is that
487           Inline writes to a build area on your disk whenever it compiles
488           code. Most CGI scripts don't (and shouldn't) be able to create a
489           directory and write into it.
490
491           The solution is to explicitly tell Inline which directory to use
492           with the 'use Inline Config => DIRECTORY => ...' line. Then you
493           need to give write access to that directory from the web server
494           (CGI script).
495
496           If you see this as a security hole, then there is another option.
497           Give write access to yourself, but read-only access to the CGI
498           script. Then run the script once by hand (from the command line).
499           This will cause Inline to precompile the C code. That way the CGI
500           will only need read access to the build directory (to load in the
501           shared library from there).
502
503           Just remember that whenever you change the C code, you need to
504           precompile it again.
505
506       See Also
507           See CGI for more information on using the "CGI.pm" module.
508
509       Credits
510
511   mod_perl
512       Problem
513
514       How do I use Inline with mod_perl?
515
516       Solution
517               package Factorial;
518               use strict;
519               use Inline Config =>
520                          DIRECTORY => '/usr/local/apache/Inline',
521                          enable => 'UNTAINT';
522               use Inline 'C';
523               Inline->init;
524
525               sub handler {
526                 my $r = shift;
527                 $r->send_http_header('text/plain');
528                 printf "%3d! = %10d\n", $_, factorial($_) for 1..100;
529                 return Apache::Constants::OK;
530               }
531
532               1;
533               __DATA__
534               __C__
535               double factorial(double x) {
536                 if (x < 2) return 1;
537                 return x * factorial(x - 1)
538               }
539
540       Discussion
541           This is a fully functional mod_perl handler that prints out the
542           factorial values for the numbers 1 to 100. Since we are using
543           Inline under mod_perl, there are a few considerations to , um,
544           consider.
545
546           First, mod_perl handlers are usually run with "-T" taint detection.
547           Therefore, we need to enable the UNTAINT option. The next thing to
548           deal with is the fact that this handler will most likely be loaded
549           after Perl's compile time. Since we are using the DATA section, we
550           need to use the special "init()" call. And of course we need to
551           specify a DIRECTORY that mod_perl can compile into. See the above
552           CGI example for more info.
553
554           Other than that, this is a pretty straightforward mod_perl handler,
555           tuned for even more speed!
556
557       See Also
558           See Stas Bekman's upcoming O'Reilly book on mod_perl to which this
559           example was contributed.
560
561   Object Oriented Inline
562       Problem
563
564       How do I implement Object Oriented programming in Perl using C objects?
565
566       Solution
567               my $obj1 = Soldier->new('Benjamin', 'Private', 11111);
568               my $obj2 = Soldier->new('Sanders', 'Colonel', 22222);
569               my $obj3 = Soldier->new('Matt', 'Sergeant', 33333);
570
571               for my $obj ($obj1, $obj2, $obj3) {
572                 print $obj->get_serial, ") ",
573                       $obj->get_name, " is a ",
574                       $obj->get_rank, "\n";
575               }
576
577               #---------------------------------------------------------
578
579               package Soldier;
580
581               use Inline C => <<'END';
582
583               /*
584               Allocate memory with Newx if it's
585               available - if it's an older perl
586               that doesn't have Newx then we
587               resort to using New.
588               */
589               #ifndef Newx
590               #  define Newx(v,n,t) New(0,v,n,t)
591               #endif
592
593               typedef struct {
594                 char* name;
595                 char* rank;
596                 long  serial;
597               } Soldier;
598
599               SV* new(const char * classname, const char * name,
600                       const char * rank, long serial) {
601                 Soldier * soldier;
602                 SV      * obj;
603                 SV      * obj_ref;
604
605                 Newx(soldier, 1, Soldier);
606                 soldier->name = savepv(name);
607                 soldier->rank = savepv(rank);
608                 soldier->serial = serial;
609
610                 obj = newSViv((IV)soldier);
611                 obj_ref = newRV_noinc(obj);
612                 sv_bless(obj_ref, gv_stashpv(classname, GV_ADD));
613                 SvREADONLY_on(obj);
614
615                 return obj_ref;
616               }
617
618               char* get_name(SV* obj) {
619                 return ((Soldier*)SvIV(SvRV(obj)))->name;
620               }
621
622               char* get_rank(SV* obj) {
623                 return ((Soldier*)SvIV(SvRV(obj)))->rank;
624               }
625
626               long get_serial(SV* obj) {
627                 return ((Soldier*)SvIV(SvRV(obj)))->serial;
628               }
629
630               void DESTROY(SV* obj) {
631                 Soldier* soldier = (Soldier*)SvIV(SvRV(obj));
632                 Safefree(soldier->name);
633                 Safefree(soldier->rank);
634                 Safefree(soldier);
635               }
636
637               END
638
639       Discussion
640
641       Damian Conway has given us myriad ways of implementing OOP in Perl.
642       This is one he might not have thought of.
643
644       The interesting thing about this example is that it uses Perl for all
645       the OO bindings while using C for the attributes and methods.
646
647       If you examine the Perl code everything looks exactly like a regular OO
648       example. There is a "new" method and several accessor methods. The
649       familiar 'arrow syntax' is used to invoke them.
650
651       In the class definition (second part) the Perl "package" statement is
652       used to name the object class or namespace. But that's where the
653       similarities end Inline takes over.
654
655       The idea is that we call a C subroutine called "new()" which returns a
656       blessed scalar. The scalar contains a readonly integer which is a C
657       pointer to a Soldier struct. This is our object.
658
659       The "new()" function needs to malloc the memory for the struct and then
660       copy the initial values into it using "savepv()". This also allocates
661       more memory (which we have to keep track of).
662
663       The accessor methods are pretty straightforward. They return the
664       current value of their attribute.
665
666       The last method "DESTROY()" is called automatically by Perl whenever an
667       object goes out of scope. This is where we can free all the memory used
668       by the object.
669
670       That's it. It's a very simplistic example. It doesn't show off any
671       advanced OO features, but it is pretty cool to see how easy the
672       implementation can be. The important Perl call is "newSVrv()" which
673       creates a blessed scalar.
674
675       See Also
676
677       Read "Object Oriented Perl" by Damian Conway, for more useful ways of
678       doing OOP in Perl.
679
680       You can learn more Perl calls in perlapi. If you don't have Perl 5.6.0
681       or higher, visit <http://www.perldoc.com/perl5.6/pod/perlapi.html>
682

THE MAIN COURSE

684   Exposing Shared Libraries
685       Problem
686           You have this great C library and you want to be able to access
687           parts of it with Perl.
688
689       Solution
690               print get('http://www.axkit.org');
691
692               use Inline C => Config =>
693                          LIBS => '-lghttp';
694               use Inline C => <<'END_OF_C_CODE';
695
696               #include <ghttp.h>
697
698               char *get(SV* uri) {
699                 SV* buffer;
700                 ghttp_request* request;
701
702                 buffer = NEWSV(0,0);
703                 request = ghttp_request_new();
704                 ghttp_set_uri(request, SvPV(uri, PL_na));
705
706                 ghttp_set_header(request, http_hdr_Connection, "close");
707
708                 ghttp_prepare(request);
709                 ghttp_process(request);
710
711                 sv_catpv(buffer, ghttp_get_body(request));
712
713                 ghttp_request_destroy(request);
714
715                 return SvPV(buffer, PL_na);
716               }
717
718               END_OF_C_CODE
719
720       Discussion
721           This example fetches and prints the HTML from
722           <http://www.axkit.org> Itrequires the GNOME http libraries.
723           <http://www.gnome.org>
724
725           One of the most common questions I get is "How can I use Inline to
726           make use of some shared library?". Although it has always been
727           possible to do so, the configuration was ugly, and there were no
728           specific examples.
729
730           With version 0.30 and higher, you can specify the use of shared
731           libraries easily with something like this:
732
733               use Inline C => Config => LIBS => '-lghttp';
734               use Inline C => "code ...";
735
736           or
737
738               use Inline C => "code ...", LIBS => '-lghttp';
739
740           To specify a specific library path, use:
741
742               use Inline C => "code ...", LIBS => '-L/your/lib/path -lyourlib';
743
744           To specify an include path use:
745
746               use Inline C => "code ...",
747                          LIBS => '-lghttp',
748                          INC => '-I/your/inc/path';
749
750       See Also
751           The "LIBS" and "INC" configuration options are formatted and passed
752           into MakeMaker. For more info see ExtUtils::MakeMaker. For more
753           options see Inline::C.
754
755       Credits
756           This code was written by Matt Sergeant <matt@sergeant.org>, author
757           of many CPAN modules. The configuration syntax has been modified
758           for use with Inline v0.30.
759
760   Automatic Function Wrappers
761       Problem
762           You have some functions in a C library that you want to access from
763           Perl exactly as you would from C.
764
765       Solution
766           The error function "erf()" is probably defined in your standard
767           math library.  Annoyingly, Perl does not let you access it. To
768           print out a small table of its values, just say:
769
770               perl -le 'use Inline C => q{ double erf(double); }, enable => "autowrap"; print "$_ @{[erf($_)]}" for (0..10)'
771
772           The excellent "Term::ReadLine::Gnu" implements Term::ReadLine using
773           the GNU ReadLine library. Here is an easy way to access just
774           "readline()" from that library:
775
776               package MyTerm;
777
778               use Inline C => Config =>
779                          enable => autowrap =>
780                          LIBS => "-lreadline -lncurses -lterminfo -ltermcap ";
781               use Inline C => q{ char * readline(char *); };
782
783               package main;
784               my $x = MyTerm::readline("xyz: ");
785
786           Note however that it fails to "free()" the memory returned by
787           readline, and that "Term::ReadLine::Gnu" offers a much richer
788           interface.
789
790       Discussion
791           We access existing functions by merely showing Inline their
792           declarations, rather than a full definition. Of course the function
793           declared must exist, either in a library already linked to Perl or
794           in a library specified using the "LIBS" option.
795
796           The first example wraps a function from the standard math library,
797           so Inline requires no additional "LIBS" directive. The second uses
798           the Config option to specify the libraries that contain the actual
799           compiled C code.
800
801           This behavior is always disabled by default. You must enable the
802           "autowrap" option to make it work.
803
804       See Also
805           ·   "readline"
806
807           ·   "Term::ReadLine::Gnu"
808
809       Credits
810           GNU ReadLine was written by Brian Fox <bfox@ai.mit.edu> and Chet
811           Ramey <chet@ins.cwru.edu>. Term::ReadLine::Gnu was written by Hiroo
812           Hayashi <hiroo.hayashi@computer.org>. Both are far richer than the
813           slim interface given here!
814
815           The idea of producing wrapper code given only a function
816           declaration is taken from Swig by David M. Beazley
817           <beazley@cs.uchicago.edu>.
818
819           Ingy's inline editorial insight:
820
821           This entire entry was contributed by Ariel Scolnicov
822           <ariels@compugen.co.il>.  Ariel also first suggested the idea for
823           Inline to support function declaration processing.
824
825   Replacing h2xs
826       Problem
827           You have a complete C library that you want to access from Perl
828           exactly as you would from C.
829
830       Solution
831           Just say:
832
833               use IO::All;
834               use Inline C => sub { io('allheaders.h')->all =~ s/LEPT_DLL extern//gr },
835                 enable => "autowrap",
836                 libs => '-lleptonica';
837
838       Discussion
839           In principle, you can use h2xs to wrap a C library into an XS
840           module. One problem with this is that the C parser code is a little
841           out of date. Also, since it works by generating a number of files,
842           maintaining it when the C library changes is a certain amount of
843           work. Using Inline to do the work is much easier.
844
845           If the header file needs some processing, like removing some text
846           that a full C compiler can deal with, but the Inline::C parser
847           cannot, as in the example above? Well, Perl is good at text-
848           processing.
849
850   Complex Data
851       Problem
852
853       How do I deal with complex data types like hashes in Inline C?
854
855       Solution
856               use Inline C => <<'END_OF_C_CODE';
857
858               void dump_hash(SV* hash_ref) {
859                 HV* hash;
860                 HE* hash_entry;
861                 int num_keys, i;
862                 SV* sv_key;
863                 SV* sv_val;
864
865                 if (! SvROK(hash_ref))
866                   croak("hash_ref is not a reference");
867
868                 hash = (HV*)SvRV(hash_ref);
869                 num_keys = hv_iterinit(hash);
870                 for (i = 0; i < num_keys; i++) {
871                   hash_entry = hv_iternext(hash);
872                   sv_key = hv_iterkeysv(hash_entry);
873                   sv_val = hv_iterval(hash, hash_entry);
874                   printf("%s => %s\n", SvPV(sv_key, PL_na), SvPV(sv_val, PL_na));
875                 }
876                 return;
877               }
878
879               END_OF_C_CODE
880
881               my %hash = (
882                 Author => "Ingy döt Net",
883                 Nickname => "INGY",
884                 Module => "Inline.pm",
885                 Version => "0.30",
886                 Language => "C",
887               );
888
889               dump_hash(\%hash);
890
891       Discussion
892           The world is not made of scalars alone, although they are
893           definitely the easiest creatures to deal with, when doing Inline
894           stuff. Sometimes we need to deal with arrays, hashes, and code
895           references, among other things.
896
897           Since Perl subroutine calls only pass scalars as arguments, we'll
898           need to use the argument type "SV*" and pass references to more
899           complex types.
900
901           The above program dumps the key/value pairs of a hash. To figure it
902           out, just curl up with perlapi for a couple hours. Actually, its
903           fairly straight forward once you are familiar with the calls.
904
905           Note the "croak" function call. This is the proper way to die from
906           your C extensions.
907
908       See Also
909           See perlapi for information about the Perl5 internal API.
910
911       Credits
912
913   Hash of Lists
914       Problem
915
916       How do I create a Hash of Lists from C?
917
918       Solution
919               use Inline 'C';
920               use Data::Dumper;
921
922               $hash_ref = load_data("./cartoon.txt");
923               print Dumper $hash_ref;
924
925               __END__
926               __C__
927
928               static int next_word(char**, char*);
929
930               SV* load_data(char* file_name) {
931                 char buffer[100], word[100], * pos;
932                 AV* array;
933                 HV* hash = newHV();
934                 FILE* fh = fopen(file_name, "r");
935
936                 while (fgets(pos = buffer, sizeof(buffer), fh)) {
937                   if (next_word(&pos, word)) {
938                     array = newAV();
939                     hv_store(hash, word, strlen(word),
940                       newRV_noinc((SV*)array), 0);
941                     while (next_word(&pos, word))
942                       av_push(array, newSVpvf("%s", word));
943                   }
944                 }
945                 fclose(fh);
946                 return newRV_noinc((SV*) hash);
947               }
948
949               static int next_word(char** text_ptr, char* word) {
950                 char* text = *text_ptr;
951                 while(*text != '\0' &&
952                       *text <= ' ')
953                   text++;
954                 if (*text <= ' ')
955                   return 0;
956                 while(*text != '\0' &&
957                       *text > ' ') {
958                   *word++ = *text++;
959                 }
960                 *word = '\0';
961                 *text_ptr = text;
962                 return 1;
963               }
964
965       Discussion
966           This is one of the larger recipes. But when you consider the number
967           of calories it has, it's not so bad. The function "load_data" takes
968           the name of a file as it's input. The file "cartoon.text" might
969           look like:
970
971               flintstones fred barney
972               jetsons     george jane elroy
973               simpsons    homer marge bart
974
975           The function will read the file, parsing each line into words. Then
976           it will create a new hash, whereby the first word in a line becomes
977           a hash key and the remaining words are put into an array whose
978           reference becomes the hash value.  The output looks like this:
979
980               $VAR1 = {
981                         'flintstones' => [
982                                            'fred',
983                                            'barney'
984                                          ],
985                         'simpsons' => [
986                                         'homer',
987                                         'marge',
988                                         'bart'
989                                       ],
990                         'jetsons' => [
991                                        'george',
992                                        'jane',
993                                        'elroy'
994                                      ]
995                       };
996
997       See Also
998           See perlapi for information about the Perl5 internal API.
999
1000       Credits
1001           Al Danial <alnd@pacbell.net> requested a solution to this on
1002           comp.lang.perl.misc. He borrowed the idea from the "Hash of Lists"
1003           example in the Camel book.
1004

JUST DESSERTS

1006   Win32
1007       Problem
1008           How do I access Win32 DLL-s using Inline?
1009
1010       Solution
1011               use Inline C => DATA =>
1012                          LIBS => '-luser32';
1013
1014               $text = "@ARGV" || 'Inline.pm works with MSWin32. Scary...';
1015
1016               WinBox('Inline Text Box', $text);
1017
1018               __END__
1019               __C__
1020
1021               #include <windows.h>
1022
1023               int WinBox(char* Caption, char* Text) {
1024                 return MessageBoxA(0, Text, Caption, 0);
1025               }
1026
1027       Discussion
1028           This example runs on MS Windows. It makes a text box appear on the
1029           screen which contains a message of your choice.
1030
1031           The important thing is that its proof that you can use Inline to
1032           interact with Windows DLL-s. Very scary indeed. 8-o
1033
1034           To use Inline on Windows with ActivePerl (
1035           <http://www.ActiveState.com> )you'll need MS Visual Studio. You can
1036           also use the Cygwin environment,available at
1037           <http://www.cygwin.com> .
1038
1039       See Also
1040           See Inline-Support for more info on MSWin32 programming with
1041           Inline.
1042
1043       Credits
1044           This example was adapted from some sample code written by Garrett
1045           Goebel <garrett@scriptpro.com>
1046
1047   Embedding Perl in C
1048       Problem
1049           How do I use Perl from a regular C program?
1050
1051       Solution
1052               #!/usr/bin/cpr
1053
1054               int main(void) {
1055                 printf("Using Perl version %s from a C program!\n\n",
1056                        CPR_eval("use Config; $Config{version};"));
1057
1058                 CPR_eval("use Data::Dumper;");
1059                 CPR_eval("print Dumper \\%INC;");
1060
1061                 return 0;
1062               }
1063
1064       Discussion
1065           By using CPR. (C Perl Run)
1066
1067           This example uses another Inline module, "Inline::CPR", available
1068           separately on CPAN. When you install this module it also installs a
1069           binary interpreter called "/usr/bin/cpr". (The path may be
1070           different on your system)
1071
1072           When you feed a C program to the CPR interpreter, it automatically
1073           compiles and runs your code using Inline. This gives you full
1074           access to the Perl internals. CPR also provides a set of easy to
1075           use C macros for calling Perl internals.
1076
1077           This means that you can effectively "run" C source code by putting
1078           a CPR hashbang as the first line of your C program.
1079
1080       See Also
1081           See Inline::CPR for more information on using CPR.
1082
1083           "Inline::CPR" can be obtained from
1084           <http://search.cpan.org/search?dist=Inline-CPR>
1085
1086       Credits
1087           Randal Schwartz <merlyn@stonehenge.com>, Randolph Bentson
1088           <bentson@grieg.holmsjoen.com>, Richard Anderson
1089           <starfire@zipcon.net>, and Tim Maher <tim@consultix-inc.com> helped
1090           me figure out how to write a program that would work as a hashbang.
1091

ENTERTAINING GUESTS

1093       As of version 0.30, Inline has the ability to work in cooperation with
1094       other modules that want to expose a C API of their own. The general
1095       syntax for doing this is:
1096
1097           use Inline with => 'Module';
1098           use Inline C => ... ;
1099
1100       This tells "Module" to pass configuration options to Inline. Options
1101       like typemaps, include paths, and external libraries, are all resolved
1102       automatically so you can just concentrate on writing the functions.
1103
1104   Event handling with Event.pm
1105       Problem
1106           You need to write a C callback for the "Event.pm" module. Can this
1107           be done more easily with Inline?
1108
1109       Solution
1110               use Inline with => 'Event';
1111
1112               Event->timer(desc     => 'Timer #1',
1113                            interval => 2,
1114                            cb       => \&my_callback,
1115                           );
1116
1117               Event->timer(desc     => 'Timer #2',
1118                            interval => 3,
1119                            cb       => \&my_callback,
1120                           );
1121
1122               print "Starting...\n";
1123               Event::loop;
1124
1125               use Inline C => <<'END';
1126               void my_callback(pe_event* event) {
1127                 pe_timer * watcher = event->up;
1128
1129                 printf("%s\n\tEvent priority = %d\n\tWatcher priority = %d\n\n",
1130                        SvPVX(watcher->base.desc),
1131                        event->prio,
1132                        watcher->base.prio
1133                       );
1134               }
1135               END
1136
1137       Discussion
1138           The first line tells Inline to load the "Event.pm" module. Inline
1139           then queries "Event" for configuration information. It gets the
1140           name and location of Event's header files, typemaps and shared
1141           objects. The parameters that "Event" returns look like:
1142
1143               INC => "-I $path/Event",
1144               TYPEMAPS => "$path/Event/typemap",
1145               MYEXTLIB => "$path/auto/Event/Event.$so",
1146               AUTO_INCLUDE => '#include "EventAPI.h"',
1147               BOOT => 'I_EVENT_API("Inline");',
1148
1149           Doing all of this automatically allows you, the programmer, to
1150           simply write a function that receives a pointer of type
1151           'pe_event*'. This gives you access to the "Event" structure that
1152           was passed to you.
1153
1154           In this example, I simply print values out of the structure. The
1155           Perl code defines 2 timer events which each invoke the same
1156           callback. The first one, every two seconds, and the second one,
1157           every three seconds.
1158
1159           As of this writing, "Event.pm" is the only CPAN module that works
1160           in cooperation with Inline.
1161
1162       See Also
1163           Read the "Event.pm" documentation for more information. It contains
1164           a tutorial showing several examples of using Inline with "Event".
1165
1166       Credits
1167           Jochen Stenzel <perl@jochen-stenzel.de> originally came up with the
1168           idea of mixing Inline and "Event". He also authored the "Event"
1169           tutorial.
1170
1171           Joshua Pritikin <joshua.pritikin@db.com> is the author of
1172           "Event.pm".
1173

FOOD FOR THOUGHT

1175   Calling C from both Perl and C
1176       Problem
1177           I'd like to be able to call the same C function from both Perl and
1178           C.  Also I like to define a C function that doesn't get bound to
1179           Perl. How do I do that?
1180
1181       Solution
1182               print "9 + 5 = ", add(9, 5), "\n";
1183               print "SQRT(9^2 + 5^2) = ", pyth(9, 5), "\n";
1184               print "9 * 5 = ", mult(9, 5), "\n";
1185
1186               use Inline C => <<'END_C';
1187               int add(int x, int y) {
1188                 return x + y;
1189               }
1190               static int mult(int x, int y) {
1191                 return x * y;
1192               }
1193               double pyth(int x, int y) {
1194                 return sqrt(add(mult(x, x), mult(y, y)));
1195               }
1196               END_C
1197
1198       Discussion
1199           The program produces:
1200
1201               9 + 5 = 14
1202               SQRT(9^2 + 5^2) = 10.295630140987
1203               Can't locate auto/main/mult.al in @INC ...
1204
1205           Every Inline function that is bound to Perl is also callable by C.
1206           You don't have to do anything special. Inline arranges it so that
1207           all the typemap code gets done by XS and is out of sight. By the
1208           time the C function receives control, everything has been converted
1209           from Perl to C.
1210
1211           Of course if your function manipulates the Perl Stack, you probably
1212           don't want to call it from C (unless you really know what you're
1213           doing).
1214
1215           If you declare a function as "static", Inline won't bind it to
1216           Perl. That's why we were able to call "mult()" from C but the call
1217           failed from Perl.
1218
1219   Calling Perl from C
1220       Problem
1221           So now that I can call C from Perl, how do I call a Perl subroutine
1222           from an Inline C function.
1223
1224       Solution
1225               use Inline 'C';
1226
1227               for(1..5) {
1228                 c_func_1('This is the first line');
1229                 c_func_2('This is the second line');
1230                 print "\n";
1231               }
1232
1233               sub perl_sub_1 {
1234                 print map "$_\n", @_;
1235               }
1236
1237               __DATA__
1238               __C__
1239
1240               void c_func_2(SV* text) {
1241                 dSP;
1242
1243                 ENTER;
1244                 SAVETMPS;
1245
1246                 XPUSHs(sv_2mortal(newSVpvf("Plus an extra line")));
1247                 PUTBACK;
1248
1249                 call_pv("perl_sub_1", G_DISCARD);
1250
1251                 FREETMPS;
1252                 LEAVE;
1253               }
1254
1255               void c_func_1(SV* text) {
1256                 c_func_2(text);
1257               }
1258
1259       Discussion
1260           This demo previously made use of Inline Stack macros only - but
1261           that's not the correct way to do it. Instead, base the callbacks on
1262           the perlcall documentation (as we're now doing).
1263
1264           Actually, this program demonstrates calling a C function which
1265           calls another C function which in turn calls a Perl subroutine.
1266
1267           The nice thing about Inline C functions is that you can call them
1268           from both Perl-space and C-space. That's because Inline creates a
1269           wrapper function around each C function. When you use Perl to call
1270           C you're actually calling that function's wrapper. The wrapper
1271           handles typemapping and Stack management, and then calls your C
1272           function.
1273
1274           The first time we call "c_func_1" which calls "c_func_2". The
1275           second time we call "c_func_2" directly. "c_func_2" calls the Perl
1276           subroutine ("perl_sub_1") using the internal "perl_call_pv"
1277           function. It has to put arguments on the stack by hand. Since there
1278           is already one argument on the stack when we enter the function,
1279           the "XPUSHs" ( which is equivalent to an "Inline_Stack_Push" ) adds
1280           a second argument.
1281
1282           We iterate through a 'for' loop 5 times just to demonstrate that
1283           things still work correctly when we do that. (This was where the
1284           previous rendition, making use solely of Inline Stack macros, fell
1285           down.)
1286
1287       See Also
1288           See Inline::C for more information about Stack macros.
1289
1290           See perlapi for more information about the Perl5 internal API.
1291
1292   Evaling C
1293       Problem
1294           I've totally lost my marbles and I want to generate C code at run
1295           time, and "eval" it into Perl. How do I do this?
1296
1297       Solution
1298               use Inline;
1299               use Code::Generator;
1300
1301               my $c_code = generate('foo_function');
1302
1303               Inline->bind(C => $c_code);
1304
1305               foo_function(1, 2, 3);
1306
1307       Discussion
1308           I can't think of a real life application where you would want to
1309           generate C code on the fly, but at least I know how I would do it.
1310           :)
1311
1312           The "bind()" function of Inline let's you bind (compileloadexecute)
1313           C functions at run time. It takes all of the same arguments as "use
1314           Inline C => ...".
1315
1316           The nice thing is that once a particular snippet is compiled, it
1317           remains cached so that it doesn't need to be compiled again. I can
1318           imagine that someday a mad scientist will dream up a self
1319           generating modeling system that would run faster and faster over
1320           time.
1321
1322           If you know such a person, have them drop me a line.
1323
1324   Providing a pure perl alternative
1325       Problem
1326           I want to write a script that will use a C subroutine if Inline::C
1327           is installed, but will otherwise use an equivalent pure perl
1328           subroutine if Inline::C is not already installed. How do I do this?
1329
1330       Solution
1331               use strict;
1332               use warnings;
1333
1334               eval {
1335                 require Inline;
1336                 Inline->import (C => Config =>
1337                                 BUILD_NOISY => 1);
1338                 Inline->import (C =><<'EOC');
1339
1340                 int foo() {
1341                   warn("Using Inline\n");
1342                   return 42;
1343                 }
1344
1345               EOC
1346               };
1347
1348               if ($@) {
1349                 *foo =\&bar;
1350               }
1351
1352               sub bar {
1353                 warn("Using Pure Perl Implementation\n");
1354                 return 42;
1355               }
1356
1357               my $x = foo();
1358               print "$x\n";
1359
1360       Discussion
1361           If Inline::C is installed and functioning properly, the C sub foo
1362           is called by the perl code. Otherwise, $@ gets set, and the
1363           equivalent pure perl function bar is instead called.
1364
1365           Note, too, that the pure perl sub bar can still be explicitly
1366           called even if Inline::C is available.
1367
1368   Accessing Fortran subs using Inline::C
1369       Problem
1370           I've been given a neat little sub written in fortran that takes, as
1371           its args, two integers and returns their product. And I would like
1372           to use that sub as is from Inline::C. By way of example, let's say
1373           that the fortran source file is named 'prod.f', and that it looks
1374           like this:
1375
1376               integer function sqarea(r,s)
1377               integer r, s
1378               sqarea = r*s
1379               return
1380               end
1381
1382       Solution
1383           We can't access that code directly, but we can compile it into a
1384           library which we can then access from Inline::C. Using gcc we could
1385           run:
1386
1387               gfortran -c prod.f -o prod.o
1388               ar cru libprod.a prod.o
1389
1390           The function is then accessible as follows:
1391
1392               use warnings;
1393
1394               use Inline C => Config =>
1395                 LIBS => '-L/full/path/to/libprod_location -lprod -lgfortran';
1396
1397               use Inline C => <<'  EOC';
1398
1399               int wrap_sqarea(int a, int b) {
1400                 return sqarea_(&a, &b);
1401               }
1402
1403               EOC
1404
1405               $x = 15;
1406               $y = $x + 3;
1407               $ret = wrap_sqarea($x, $y);
1408               print "Product of $x and $y is $ret\n";
1409
1410       Discussion
1411           Note firstly that, although the function is specified as 'sqarea'
1412           in the source file, gfortran appends an underscore to the name when
1413           the source is compiled. (I don't know if all fortran compilers do
1414           this.) Therefore Inline::C needs to call the function as 'sqarea_'.
1415
1416           Secondly, because fortran subs pass args by reference, we need to
1417           pass the addresses of the two integer args to sqarea() when we call
1418           it from our Inline::C sub.
1419
1420           If using g77 instead of gfortran, the only necessary change is that
1421           we specify '-lg2c' instead of '-lgfortran' in our 'LIBS' setting.
1422

SEE ALSO

1424       For generic information about Inline, see Inline.
1425
1426       For information about using Inline with C see Inline::C.
1427
1428       For information on supported languages and platforms see Inline-
1429       Support.
1430
1431       For information on writing your own Inline language support module, see
1432       Inline-API.
1433
1434       Inline's mailing list is inline@perl.org
1435
1436       To subscribe, send email to inline-subscribe@perl.org
1437

AUTHORS

1439       Ingy döt Net <ingy@cpan.org>
1440
1441       Sisyphus <sisyphus@cpan.org>
1442
1444       Copyright 2000-2019. Ingy döt Net.
1445
1446       Copyright 2008, 2010-2014. Sisyphus.
1447
1448       This program is free software; you can redistribute it and/or modify it
1449       under the same terms as Perl itself.
1450
1451       See <http://www.perl.com/perl/misc/Artistic.html>
1452
1453
1454
1455perl v5.32.0                      2020-07-28            Inline::C::Cookbook(3)
Impressum