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 he
315           is close (<http://bike-nomad.com).> Thanks Ned.
316
317   Using Memory
318       Problem
319           How should I allocate buffers in my Inline C code?
320
321       Solution
322               print greeting('Ingy');
323
324               use Inline C => <<'END_OF_C_CODE';
325
326               SV* greeting(SV* sv_name) {
327                 return (newSVpvf("Hello %s!\n", SvPV(sv_name, PL_na)));
328               }
329
330               END_OF_C_CODE
331
332       Discussion
333           In this example we will return the greeting to the caller, rather
334           than printing it. This would seem mighty easy, except for the fact
335           that we need to allocate a small buffer to create the greeting.
336
337           I would urge you to stay away from "malloc"ing your own buffer.
338           Just use Perl's built in memory management. In other words, just
339           create a new Perl string scalar. The function "newSVpv" does just
340           that. And "newSVpvf" includes "sprintf" functionality.
341
342           The other problem is getting rid of this new scalar. How will the
343           ref count get decremented after we pass the scalar back? Perl also
344           provides a function called "sv_2mortal". Mortal variables die when
345           the context goes out of scope.  In other words, Perl will wait
346           until the new scalar gets passed back and then decrement the ref
347           count for you, thereby making it eligible for garbage collection.
348           See "perldoc perlguts".
349
350           In this example the "sv_2mortal" call gets done under the hood by
351           XS, because we declared the return type to be "SV*".
352
353           To view the generated XS code, run the command ""perl -
354           MInline=INFO,FORCE,NOCLEAN example004.pl"". This will leave the
355           build directory intact and tell you where to find it.
356
357       See Also
358       Credits
359
360   Direct Access to Perl variables
361       Problem
362           Can I write an Inline C function that can access a Perl variable
363           directly without having to pass it as an argument?
364
365       Solution
366               use strict;
367               use warnings;
368               use Inline C => "DATA";
369
370               our $mesh_data = "MESH-POINTS 0.0 0.0 0.5 0.25 1.0 0.5 1.5 0.75";
371               CalcSurfaceHeights();
372
373               __DATA__
374               __C__
375               #define N_MP 4
376
377               void CalcSurfaceHeights() {
378                  double x[N_MP], y[N_MP], z;
379                  int    ix;
380                  char   *mesh_data = SvPV_nolen(get_sv("main::mesh_data", 0));
381
382                  sscanf(mesh_data, "MESH-POINTS %lf%lf%lf%lf%lf%lf%lf%lf",
383                                    x, y, x+1, y+1, x+2, y+2, x+3, y+3);
384
385                  for (ix=0; ix < N_MP; ix++) {
386                     z = 0.5*( sin(x[ix]) + sin(y[ix]) );
387
388                     printf("Surface-Height: %6.3f Mesh-Point: %6.2f, %6.2f\n",
389                            z, x[ix], y[ix]);
390                  }
391               }
392
393       Discussion
394           There are really only two points that need an explanation to
395           understand why the above code works. In the Perl section, you will
396           notice the declaration
397
398               our $mesh_data = "...";
399
400           For Perl variables to be directly accessible from Inline::C
401           functions, they must be declared as package variables. Lexical
402           variables, those declared with my, cannot be accessed this way.
403
404           In the C code section of the example, the following line is what
405           makes direct access to the Perl variable work;
406
407               char *mesh_data = SvPV_nolen(get_sv("main::mesh_data", 0))
408
409           Here SvPV_nolen() returns a pointer to the C string contained in
410           the scalar variable. The "_nolen" variation ignores the length of
411           the C string. Hence, the function takes only a single argument,
412           which is the SV* of the scalar variable.
413
414           We could have used the usual two-argument form of SvPV() and, since
415           we don't care about the string length, specified PL_na for the
416           second argument. The function call would then change to,
417
418               SvPV(get_sv("main::mesh_data", 0), PL_na)
419
420           The function get_sv() returns the SV* of a named scalar package
421           variable.  It takes a C string, containing the fully qualified name
422           of the variable, as the first argument. The second argument
423           contains flag values related to data type. Since we are only
424           reading the scalar variable, in our example, a value of 0 can be
425           used.
426
427       See Also
428           ·   perldoc perlguts
429
430           ·   perldoc perlapi
431
432       Credits
433           The code example and description were inspired by a discussion
434           thread on the Inline mailing list (inline@perl.org).
435

FAST FOOD

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

THE MAIN COURSE

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

JUST DESSERTS

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

ENTERTAINING GUESTS

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

FOOD FOR THOUGHT

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

SEE ALSO

1399       For generic information about Inline, see Inline.
1400
1401       For information about using Inline with C see Inline::C.
1402
1403       For information on supported languages and platforms see Inline-
1404       Support.
1405
1406       For information on writing your own Inline language support module, see
1407       Inline-API.
1408
1409       Inline's mailing list is inline@perl.org
1410
1411       To subscribe, send email to inline-subscribe@perl.org
1412

AUTHORS

1414       Ingy döt Net <ingy@cpan.org>
1415
1416       Sisyphus <sisyphus@cpan.org>
1417
1419       Copyright 2000-2019. Ingy döt Net.
1420
1421       Copyright 2008, 2010-2014. Sisyphus.
1422
1423       This program is free software; you can redistribute it and/or modify it
1424       under the same terms as Perl itself.
1425
1426       See <http://www.perl.com/perl/misc/Artistic.html>
1427
1428
1429
1430perl v5.28.1                      2019-04-18            Inline::C::Cookbook(3)
Impressum