.\" Automatically generated by Pod::Man 2.28 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "Inline::C::Cookbook 3pm" .TH Inline::C::Cookbook 3pm "2015-07-04" "perl v5.20.2" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Inline::C::Cookbook \- A Cornucopia of Inline C Recipes .SH "DESCRIPTION" .IX Header "DESCRIPTION" It's a lot easier for most of us to cook a meal from a recipe, rather than just throwing things into a pot until something edible forms. So it is with programming as well. \f(CW\*(C`Inline.pm\*(C'\fR makes C programming for Perl as easy as possible. Having a set of easy to understand samples, makes it simpler yet. .PP This Cookbook is intended to be an evergrowing repository of small yet complete coding examples; each showing how to accomplish a particular task with Inline. Each example is followed by a short discussion, explaining in detail the particular features that are being demonstrated. .PP Many of these recipes are adapted from email discussions I have had with Inline users around the world. It has been my experience so far, that Inline provides an elegant solution to almost all problems involving Perl and C. .PP Bon Appetit! .SH "APPETIZERS" .IX Header "APPETIZERS" .SS "Hello, world" .IX Subsection "Hello, world" .IP "Problem" 4 .IX Item "Problem" .PP It seems that the first thing any programmer wants to do when he learns a new programming technique is to use it to greet the Earth. How can I do this using Inline? .IP "Solution" 4 .IX Item "Solution" .Vb 1 \& use Inline C => <<\*(Aq...\*(Aq; \& \& void greet() { \& printf("Hello, world\en"); \& } \& ... \& \& greet; .Ve .IP "Discussion" 4 .IX Item "Discussion" Nothing too fancy here. We define a single C function \f(CW\*(C`greet()\*(C'\fR which prints a message to \s-1STDOUT.\s0 One thing to note is that since the Inline code comes before the function call to \f(CW\*(C`greet\*(C'\fR, we can call it as a bareword (no parentheses). .IP "See Also" 4 .IX Item "See Also" See Inline and Inline::C for basic info about \f(CW\*(C`Inline.pm\*(C'\fR. .IP "Credits" 4 .IX Item "Credits" .RS 4 .PD 0 .IP "\(bu" 4 .PD Brian Kernigan .IP "\(bu" 4 Dennis Ritchie .RE .RS 4 .RE .SS "One Liner" .IX Subsection "One Liner" .IP "Problem" 4 .IX Item "Problem" A concept is valid in Perl only if it can be shown to work in one line. Can Inline reduce the complexities of Perl/C interaction to a one-liner? .IP "Solution" 4 .IX Item "Solution" .Vb 1 \& perl \-e \*(Aquse Inline C=>q{void greet(){printf("Hello, world\en");}};greet\*(Aq .Ve .IP "Discussion" 4 .IX Item "Discussion" Try doing that in \s-1XS :\-\s0) .IP "See Also" 4 .IX Item "See Also" My email signature of late is: .Sp .Vb 1 \& perl \-le \*(Aquse Inline C=>q{SV*JAxH(char*x){return newSVpvf("Just Another %s Hacker",x);}};print JAxH+Perl\*(Aq .Ve .Sp A bit fancier but a few bytes too long to qualify as a true one liner :\-( .IP "Credits" 4 .IX Item "Credits" \&\*(L"Eli the Bearded\*(R" gave me the idea that I should have an Inline one-liner as a signature. .SH "MEAT & POTATOES" .IX Header "MEAT & POTATOES" .SS "Data Types" .IX Subsection "Data Types" .IP "Problem" 4 .IX Item "Problem" How do I pass different types of data to and from Inline C functions; like strings, numbers and integers? .IP "Solution" 4 .IX Item "Solution" .Vb 2 \& # vowels.pl \& use Inline C; \& \& $filename = $ARGV[0]; \& die "Usage: perl vowels.pl filename\en" unless \-f $filename; \& \& $text = join \*(Aq\*(Aq, <>; # slurp input file \& $vp = vowel_scan($text); # call our function \& $vp = sprintf("%03.1f", $vp * 100); # format for printing \& print "The letters in $filename are $vp% vowels.\en"; \& \& _\|_END_\|_ \& _\|_C_\|_ \& \& /* Find percentage of vowels to letters */ \& double vowel_scan(char* str) { \& int letters = 0; \& int vowels = 0; \& int i = 0; \& char c; \& char normalize = \*(Aqa\*(Aq ^ \*(AqA\*(Aq; \& /* normalize forces lower case in ASCII; upper in EBCDIC */ \& char A = normalize | \*(Aqa\*(Aq; \& char E = normalize | \*(Aqe\*(Aq; \& char I = normalize | \*(Aqi\*(Aq; \& char O = normalize | \*(Aqo\*(Aq; \& char U = normalize | \*(Aqu\*(Aq; \& char Z = normalize | \*(Aqz\*(Aq; \& \& while(c = str[i++]) { \& c |= normalize; \& if (c >= A && c <= Z) { \& letters++; \& if (c == A || c == E || c == I || c == O || c == U) \& vowels++; \& } \& } \& \& return letters ? ((double) vowels / letters) : 0.0; \& } .Ve .IP "Discussion" 4 .IX Item "Discussion" This script takes a file name from the command line and prints the ratio of vowels to letters in that file. \f(CW\*(C`vowels.pl\*(C'\fR uses an Inline C function called \&\f(CW\*(C`vowel_scan\*(C'\fR, that takes a string argument, and returns the percentage of vowels as a floating point number between 0 and 1. It handles upper and lower case letters, and works with \s-1ASCII\s0 and \s-1EBCDIC.\s0 It is also quite fast. .Sp Running this script produces: .Sp .Vb 2 \& > perl vowels.pl /usr/share/dict/words \& The letters in /usr/share/dict/words are 37.5% vowels. .Ve .Sp It is very important to note that the examples in this cookbook use \f(CW\*(C`char *\*(C'\fR to mean a string. Internally Perl has various mechanisms to deal with strings that contain characters with code points above 255, using Unicode. This means that naively treating strings as \f(CW\*(C`char *\*(C'\fR, an array of 8\-bit characters, can lead to problems. You need to be aware of this and consider using a \s-1UTF\-8\s0 library to deal with strings. .IP "See Also" 4 .IX Item "See Also" The Perl Journal vol #19 has an article about Inline which uses this example. .IP "Credits" 4 .IX Item "Credits" This example was reprinted by permission of The Perl Journal. It was edited to work with Inline v0.30 and higher. .SS "Variable Argument Lists" .IX Subsection "Variable Argument Lists" .IP "Problem" 4 .IX Item "Problem" .PP How do I pass a variable-sized list of arguments to an Inline C function? .IP "Solution" 4 .IX Item "Solution" .Vb 1 \& greet(qw(Sarathy Jan Sparky Murray Mike)); \& \& use Inline C => <<\*(AqEND_OF_C_CODE\*(Aq; \& \& void greet(SV* name1, ...) { \& Inline_Stack_Vars; \& int i; \& \& for (i = 0; i < Inline_Stack_Items; i++) \& printf("Hello %s!\en", SvPV(Inline_Stack_Item(i), PL_na)); \& \& Inline_Stack_Void; \& } \& \& END_OF_C_CODE .Ve .IP "Discussion" 4 .IX Item "Discussion" This little program greets a group of people, such as my coworkers. We use the \&\f(CW\*(C`C\*(C'\fR ellipsis syntax: "\f(CW\*(C`...\*(C'\fR", since the list can be of any size. .Sp Since there are no types or names associated with each argument, we can't expect \s-1XS\s0 to handle the conversions for us. We'll need to pop them off the \&\fBStack\fR ourselves. Luckily there are two functions (macros) that make this a very easy task. .Sp First, we need to begin our function with a "\f(CW\*(C`Inline_Stack_Vars\*(C'\fR" statement. This defines a few internal variables that we need to access the \fBStack\fR. Now we can use "\f(CW\*(C`Inline_Stack_Items\*(C'\fR", which returns an integer containing the number of arguments passed to us from Perl. .Sp \&\fB\s-1NOTE:\s0\fR It is important to \fIonly\fR use "\f(CW\*(C`Inline_Stack_\*(C'\fR" macros when there is an ellipsis (\f(CW\*(C`...\*(C'\fR) in the argument list, \fIor\fR the function has a return type of void. .Sp Second, we use the \f(CWInline_Stack_Item(x)\fR function to access each argument where \*(L"0 <= x < items\*(R". .Sp \&\fB\s-1NOTE:\s0\fR When using a variable length argument list, you have to specify at least one argument before the ellipsis. (On my compiler, anyway.) When \s-1XS\s0 does it's argument checking, it will complain if you pass in less than the number of \fIdefined\fR arguments. Therefore, there is currently no way to pass an empty list when a variable length list is expected. .IP "See Also" 4 .IX Item "See Also" .PD 0 .IP "Credits" 4 .IX Item "Credits" .PD .SS "Multiple Return Values" .IX Subsection "Multiple Return Values" .IP "Problem" 4 .IX Item "Problem" How do I return a list of values from a C function? .IP "Solution" 4 .IX Item "Solution" .Vb 1 \& print map {"$_\en"} get_localtime(time); \& \& use Inline C => <<\*(AqEND_OF_C_CODE\*(Aq; \& \& #include \& \& void get_localtime(SV * utc) { \& const time_t utc_ = (time_t)SvIV(utc); \& struct tm *ltime = localtime(&utc_); \& Inline_Stack_Vars; \& \& Inline_Stack_Reset; \& Inline_Stack_Push(sv_2mortal(newSViv(ltime\->tm_year))); \& Inline_Stack_Push(sv_2mortal(newSViv(ltime\->tm_mon))); \& Inline_Stack_Push(sv_2mortal(newSViv(ltime\->tm_mday))); \& Inline_Stack_Push(sv_2mortal(newSViv(ltime\->tm_hour))); \& Inline_Stack_Push(sv_2mortal(newSViv(ltime\->tm_min))); \& Inline_Stack_Push(sv_2mortal(newSViv(ltime\->tm_sec))); \& Inline_Stack_Push(sv_2mortal(newSViv(ltime\->tm_isdst))); \& Inline_Stack_Done; \& } \& END_OF_C_CODE .Ve .IP "Discussion" 4 .IX Item "Discussion" Perl is a language where it is common to return a list of values from a subroutine call instead of just a single value. C is not such a language. In order to accomplish this in C we need to manipulate the Perl call stack by hand. Luckily, Inline provides macros to make this easy. .Sp This example calls the system \f(CW\*(C`localtime\*(C'\fR, and returns each of the parts of the time struct; much like the perl builtin \f(CW\*(C`localtime()\*(C'\fR. On each stack push, we are creating a new Perl integer (\s-1SVIV\s0) and mortalizing it. The \&\fIsv_2mortal()\fR call makes sure that the reference count is set properly. Without it, the program would leak memory. .Sp \&\s-1NOTE:\s0 The \f(CW\*(C`#include\*(C'\fR statement is not really needed, because Inline automatically includes the Perl headers which include almost all standard system calls. .IP "See Also" 4 .IX Item "See Also" For more information on the Inline stack macros, see Inline::C. .IP "Credits" 4 .IX Item "Credits" Richard Anderson contributed the original idea for this snippet. .SS "Multiple Return Values (Another Way)" .IX Subsection "Multiple Return Values (Another Way)" .IP "Problem" 4 .IX Item "Problem" How can I pass back more than one value without using the Perl Stack? .IP "Solution" 4 .IX Item "Solution" .Vb 2 \& use Inline::Files; \& use Inline C; \& \& my ($foo, $bar); \& change($foo, $bar); \& \& print "\e$foo = $foo\en"; \& print "\e$bar = $bar\en"; \& \& _\|_C_\|_ \& \& int change(SV* var1, SV* var2) { \& sv_setpvn(var1, "Perl Rocks!", 11); \& sv_setpvn(var2, "Inline Rules!", 13); \& return 1; \& } .Ve .IP "Discussion" 4 .IX Item "Discussion" Most perl function interfaces return values as a list of one or more scalars. Very few like \f(CW\*(C`chomp\*(C'\fR, will modify an input scalar in place. On the other hand, in C you do this quite often. Values are passed in by reference and modified in place by the called function. .Sp It turns out that we can do that with Inline as well. The secret is to use a type of '\f(CW\*(C`SV*\*(C'\fR' for each argument that is to be modified. This ensures passing by reference, because no typemapping is needed. .Sp The function can then use the Perl5 \s-1API\s0 to operate on that argument. When control returns to Perl, the argument will retain the value set by the C function. In this example we passed in 2 empty scalars and assigned values directly to them. .IP "See Also" 4 .IX Item "See Also" .PD 0 .IP "Credits" 4 .IX Item "Credits" .PD Ned Konz brought this behavior to my attention. He also pointed out that he is not the world famous computer cyclist Steve Roberts ( but he is close ( Thanks Ned. .SS "Using Memory" .IX Subsection "Using Memory" .IP "Problem" 4 .IX Item "Problem" How should I allocate buffers in my Inline C code? .IP "Solution" 4 .IX Item "Solution" .Vb 1 \& print greeting(\*(AqIngy\*(Aq); \& \& use Inline C => <<\*(AqEND_OF_C_CODE\*(Aq; \& \& SV* greeting(SV* sv_name) { \& return (newSVpvf("Hello %s!\en", SvPV(sv_name, PL_na))); \& } \& \& END_OF_C_CODE .Ve .IP "Discussion" 4 .IX Item "Discussion" In this example we will return the greeting to the caller, rather than printing it. This would seem mighty easy, except for the fact that we need to allocate a small buffer to create the greeting. .Sp I would urge you to stay away from \f(CW\*(C`malloc\*(C'\fRing your own buffer. Just use Perl's built in memory management. In other words, just create a new Perl string scalar. The function \f(CW\*(C`newSVpv\*(C'\fR does just that. And \f(CW\*(C`newSVpvf\*(C'\fR includes \f(CW\*(C`sprintf\*(C'\fR functionality. .Sp The other problem is getting rid of this new scalar. How will the ref count get decremented after we pass the scalar back? Perl also provides a function called \f(CW\*(C`sv_2mortal\*(C'\fR. Mortal variables die when the context goes out of scope. In other words, Perl will wait until the new scalar gets passed back and then decrement the ref count for you, thereby making it eligible for garbage collection. See \f(CW\*(C`perldoc perlguts\*(C'\fR. .Sp In this example the \f(CW\*(C`sv_2mortal\*(C'\fR call gets done under the hood by \s-1XS,\s0 because we declared the return type to be \f(CW\*(C`SV*\*(C'\fR. .Sp To view the generated \s-1XS\s0 code, run the command "\f(CW\*(C`perl \- MInline=INFO,FORCE,NOCLEAN example004.pl\*(C'\fR". This will leave the build directory intact and tell you where to find it. .IP "See Also" 4 .IX Item "See Also" .PD 0 .IP "Credits" 4 .IX Item "Credits" .PD .SH "FAST FOOD" .IX Header "FAST FOOD" .SS "Inline \s-1CGI\s0" .IX Subsection "Inline CGI" .IP "Problem" 4 .IX Item "Problem" How do I use Inline securely in a \s-1CGI\s0 environment? .IP "Solution" 4 .IX Item "Solution" .Vb 1 \& #!/usr/bin/perl \& \& use CGI qw(:standard); \& use Inline Config => \& DIRECTORY => \*(Aq/usr/local/apache/Inline\*(Aq; \& \& print \& header, \& start_html(\*(AqInline CGI Example\*(Aq), \& h1(JAxH(\*(AqInline\*(Aq)), \& end_html; \& \& use Inline C => < \s-1DIRECTORY\s0 => ...' line. Then you need to give write access to that directory from the web server (\s-1CGI\s0 script). .Sp If you see this as a security hole, then there is another option. Give write access to yourself, but read-only access to the \s-1CGI\s0 script. Then run the script once by hand (from the command line). This will cause Inline to precompile the C code. That way the \s-1CGI\s0 will only need read access to the build directory (to load in the shared library from there). .Sp Just remember that whenever you change the C code, you need to precompile it again. .IP "See Also" 4 .IX Item "See Also" See \s-1CGI\s0 for more information on using the \f(CW\*(C`CGI.pm\*(C'\fR module. .IP "Credits" 4 .IX Item "Credits" .SS "mod_perl" .IX Subsection "mod_perl" .PD 0 .IP "Problem" 4 .IX Item "Problem" .PD .PP How do I use Inline with mod_perl? .IP "Solution" 4 .IX Item "Solution" .Vb 7 \& package Factorial; \& use strict; \& use Inline Config => \& DIRECTORY => \*(Aq/usr/local/apache/Inline\*(Aq, \& enable => \*(AqUNTAINT\*(Aq; \& use Inline \*(AqC\*(Aq; \& Inline\->init; \& \& sub handler { \& my $r = shift; \& $r\->send_http_header(\*(Aqtext/plain\*(Aq); \& printf "%3d! = %10d\en", $_, factorial($_) for 1..100; \& return Apache::Constants::OK; \& } \& \& 1; \& _\|_DATA_\|_ \& _\|_C_\|_ \& double factorial(double x) { \& if (x < 2) return 1; \& return x * factorial(x \- 1) \& } .Ve .IP "Discussion" 4 .IX Item "Discussion" This is a fully functional mod_perl handler that prints out the factorial values for the numbers 1 to 100. Since we are using Inline under mod_perl, there are a few considerations to , um, consider. .Sp First, mod_perl handlers are usually run with \f(CW\*(C`\-T\*(C'\fR taint detection. Therefore, we need to enable the \s-1UNTAINT\s0 option. The next thing to deal with is the fact that this handler will most likely be loaded after Perl's compile time. Since we are using the \s-1DATA\s0 section, we need to use the special \&\f(CW\*(C`init()\*(C'\fR call. And of course we need to specify a \s-1DIRECTORY\s0 that mod_perl can compile into. \fISee the above \s-1CGI\s0 example for more info.\fR .Sp Other than that, this is a pretty straightforward mod_perl handler, tuned for even more speed! .IP "See Also" 4 .IX Item "See Also" See Stas Bekman's upcoming O'Reilly book on mod_perl to which this example was contributed. .SS "Object Oriented Inline" .IX Subsection "Object Oriented Inline" .IP "Problem" 4 .IX Item "Problem" .PP How do I implement Object Oriented programming in Perl using C objects? .IP "Solution" 4 .IX Item "Solution" .Vb 3 \& my $obj1 = Soldier\->new(\*(AqBenjamin\*(Aq, \*(AqPrivate\*(Aq, 11111); \& my $obj2 = Soldier\->new(\*(AqSanders\*(Aq, \*(AqColonel\*(Aq, 22222); \& my $obj3 = Soldier\->new(\*(AqMatt\*(Aq, \*(AqSergeant\*(Aq, 33333); \& \& for my $obj ($obj1, $obj2, $obj3) { \& print $obj\->get_serial, ") ", \& $obj\->get_name, " is a ", \& $obj\->get_rank, "\en"; \& } \& \& #\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \& \& package Soldier; \& \& use Inline C => <<\*(AqEND\*(Aq; \& \& /* \& Allocate memory with Newx if it\*(Aqs \& available \- if it\*(Aqs an older perl \& that doesn\*(Aqt have Newx then we \& resort to using New. \& */ \& #ifndef Newx \& # define Newx(v,n,t) New(0,v,n,t) \& #endif \& \& typedef struct { \& char* name; \& char* rank; \& long serial; \& } Soldier; \& \& SV* new(const char * classname, const char * name, \& const char * rank, long serial) { \& Soldier * soldier; \& SV * obj; \& SV * obj_ref; \& \& Newx(soldier, 1, Soldier); \& soldier\->name = savepv(name); \& soldier\->rank = savepv(rank); \& soldier\->serial = serial; \& \& obj = newSViv((IV)soldier); \& obj_ref = newRV_noinc(obj); \& sv_bless(obj_ref, gv_stashpv(classname, GV_ADD)); \& SvREADONLY_on(obj); \& \& return obj_ref; \& } \& \& char* get_name(SV* obj) { \& return ((Soldier*)SvIV(SvRV(obj)))\->name; \& } \& \& char* get_rank(SV* obj) { \& return ((Soldier*)SvIV(SvRV(obj)))\->rank; \& } \& \& long get_serial(SV* obj) { \& return ((Soldier*)SvIV(SvRV(obj)))\->serial; \& } \& \& void DESTROY(SV* obj) { \& Soldier* soldier = (Soldier*)SvIV(SvRV(obj)); \& Safefree(soldier\->name); \& Safefree(soldier\->rank); \& Safefree(soldier); \& } \& \& END .Ve .IP "Discussion" 4 .IX Item "Discussion" .PP Damian Conway has given us myriad ways of implementing \s-1OOP\s0 in Perl. This is one he might not have thought of. .PP The interesting thing about this example is that it uses Perl for all the \s-1OO\s0 bindings while using C for the attributes and methods. .PP If you examine the Perl code everything looks exactly like a regular \s-1OO\s0 example. There is a \f(CW\*(C`new\*(C'\fR method and several accessor methods. The familiar \&'arrow syntax' is used to invoke them. .PP In the class definition (second part) the Perl \f(CW\*(C`package\*(C'\fR statement is used to name the object class or namespace. But that's where the similarities end Inline takes over. .PP The idea is that we call a C subroutine called \f(CW\*(C`new()\*(C'\fR which returns a blessed scalar. The scalar contains a readonly integer which is a C pointer to a Soldier struct. This is our object. .PP The \f(CW\*(C`new()\*(C'\fR function needs to malloc the memory for the struct and then copy the initial values into it using \f(CW\*(C`savepv()\*(C'\fR. This also allocates more memory (which we have to keep track of). .PP The accessor methods are pretty straightforward. They return the current value of their attribute. .PP The last method \f(CW\*(C`DESTROY()\*(C'\fR is called automatically by Perl whenever an object goes out of scope. This is where we can free all the memory used by the object. .PP That's it. It's a very simplistic example. It doesn't show off any advanced \s-1OO\s0 features, but it is pretty cool to see how easy the implementation can be. The important Perl call is \f(CW\*(C`newSVrv()\*(C'\fR which creates a blessed scalar. .IP "See Also" 4 .IX Item "See Also" .PP Read \*(L"Object Oriented Perl\*(R" by Damian Conway, for more useful ways of doing \&\s-1OOP\s0 in Perl. .PP You can learn more Perl calls in perlapi. If you don't have Perl 5.6.0 or higher, visit .SH "THE MAIN COURSE" .IX Header "THE MAIN COURSE" .SS "Exposing Shared Libraries" .IX Subsection "Exposing Shared Libraries" .IP "Problem" 4 .IX Item "Problem" You have this great C library and you want to be able to access parts of it with Perl. .IP "Solution" 4 .IX Item "Solution" .Vb 1 \& print get(\*(Aqhttp://www.axkit.org\*(Aq); \& \& use Inline C => Config => \& LIBS => \*(Aq\-lghttp\*(Aq; \& use Inline C => <<\*(AqEND_OF_C_CODE\*(Aq; \& \& #include \& \& char *get(SV* uri) { \& SV* buffer; \& ghttp_request* request; \& \& buffer = NEWSV(0,0); \& request = ghttp_request_new(); \& ghttp_set_uri(request, SvPV(uri, PL_na)); \& \& ghttp_set_header(request, http_hdr_Connection, "close"); \& \& ghttp_prepare(request); \& ghttp_process(request); \& \& sv_catpv(buffer, ghttp_get_body(request)); \& \& ghttp_request_destroy(request); \& \& return SvPV(buffer, PL_na); \& } \& \& END_OF_C_CODE .Ve .IP "Discussion" 4 .IX Item "Discussion" This example fetches and prints the \s-1HTML\s0 from It requires the \s-1GNOME\s0 http libraries. .Sp One of the most common questions I get is \*(L"How can I use Inline to make use of some shared library?\*(R". Although it has always been possible to do so, the configuration was ugly, and there were no specific examples. .Sp With version 0.30 and higher, you can specify the use of shared libraries easily with something like this: .Sp .Vb 2 \& use Inline C => Config => LIBS => \*(Aq\-lghttp\*(Aq; \& use Inline C => "code ..."; .Ve .Sp or .Sp .Vb 1 \& use Inline C => "code ...", LIBS => \*(Aq\-lghttp\*(Aq; .Ve .Sp To specify a specific library path, use: .Sp .Vb 1 \& use Inline C => "code ...", LIBS => \*(Aq\-L/your/lib/path \-lyourlib\*(Aq; .Ve .Sp To specify an include path use: .Sp .Vb 3 \& use Inline C => "code ...", \& LIBS => \*(Aq\-lghttp\*(Aq, \& INC => \*(Aq\-I/your/inc/path\*(Aq; .Ve .IP "See Also" 4 .IX Item "See Also" The \f(CW\*(C`LIBS\*(C'\fR and \f(CW\*(C`INC\*(C'\fR configuration options are formatted and passed into MakeMaker. For more info see ExtUtils::MakeMaker. For more options see Inline::C. .IP "Credits" 4 .IX Item "Credits" This code was written by Matt Sergeant , author of many \&\s-1CPAN\s0 modules. The configuration syntax has been modified for use with Inline v0.30. .SS "Automatic Function Wrappers" .IX Subsection "Automatic Function Wrappers" .IP "Problem" 4 .IX Item "Problem" You have some functions in a C library that you want to access from Perl exactly as you would from C. .IP "Solution" 4 .IX Item "Solution" The error function \f(CW\*(C`erf()\*(C'\fR is probably defined in your standard math library. Annoyingly, Perl does not let you access it. To print out a small table of its values, just say: .Sp .Vb 1 \& perl \-le \*(Aquse Inline C => q{ double erf(double); }, enable => "autowrap"; print "$_ @{[erf($_)]}" for (0..10)\*(Aq .Ve .Sp The excellent \f(CW\*(C`Term::ReadLine::Gnu\*(C'\fR implements Term::ReadLine using the \&\s-1GNU\s0 ReadLine library. Here is an easy way to access just \f(CW\*(C`readline()\*(C'\fR from that library: .Sp .Vb 1 \& package MyTerm; \& \& use Inline C => Config => \& enable => autowrap => \& LIBS => "\-lreadline \-lncurses \-lterminfo \-ltermcap "; \& use Inline C => q{ char * readline(char *); }; \& \& package main; \& my $x = MyTerm::readline("xyz: "); .Ve .Sp Note however that it fails to \f(CW\*(C`free()\*(C'\fR the memory returned by readline, and that \f(CW\*(C`Term::ReadLine::Gnu\*(C'\fR offers a much richer interface. .IP "Discussion" 4 .IX Item "Discussion" We access existing functions by merely showing Inline their declarations, rather than a full definition. Of course the function declared must exist, either in a library already linked to Perl or in a library specified using the \&\f(CW\*(C`LIBS\*(C'\fR option. .Sp The first example wraps a function from the standard math library, so Inline requires no additional \f(CW\*(C`LIBS\*(C'\fR directive. The second uses the Config option to specify the libraries that contain the actual compiled C code. .Sp This behavior is always disabled by default. You must enable the \f(CW\*(C`autowrap\*(C'\fR option to make it work. .IP "See Also" 4 .IX Item "See Also" .RS 4 .PD 0 .IP "\(bu" 4 .PD \&\f(CW\*(C`readline\*(C'\fR .IP "\(bu" 4 \&\f(CW\*(C`Term::ReadLine::Gnu\*(C'\fR .RE .RS 4 .RE .IP "Credits" 4 .IX Item "Credits" \&\s-1GNU\s0 ReadLine was written by Brian Fox and Chet Ramey . Term::ReadLine::Gnu was written by Hiroo Hayashi . Both are far richer than the slim interface given here! .Sp The idea of producing wrapper code given only a function declaration is taken from Swig by David M. Beazley . .Sp Ingy's inline editorial insight: .Sp This entire entry was contributed by Ariel Scolnicov . Ariel also first suggested the idea for Inline to support function declaration processing. .SS "Replacing h2xs" .IX Subsection "Replacing h2xs" .IP "Problem" 4 .IX Item "Problem" You have a complete C library that you want to access from Perl exactly as you would from C. .IP "Solution" 4 .IX Item "Solution" Just say: .Sp .Vb 4 \& use IO::All; \& use Inline C => sub { io(\*(Aqallheaders.h\*(Aq)\->all =~ s/LEPT_DLL extern//gr }, \& enable => "autowrap", \& libs => \*(Aq\-lleptonica\*(Aq; .Ve .IP "Discussion" 4 .IX Item "Discussion" In principle, you can use h2xs to wrap a C library into an \s-1XS\s0 module. One problem with this is that the C parser code is a little out of date. Also, since it works by generating a number of files, maintaining it when the C library changes is a certain amount of work. Using Inline to do the work is much easier. .Sp If the header file needs some processing, like removing some text that a full C compiler can deal with, but the Inline::C parser cannot, as in the example above? Well, Perl is good at text-processing. .SS "Complex Data" .IX Subsection "Complex Data" .IP "Problem" 4 .IX Item "Problem" .PP How do I deal with complex data types like hashes in Inline C? .IP "Solution" 4 .IX Item "Solution" .Vb 1 \& use Inline C => <<\*(AqEND_OF_C_CODE\*(Aq; \& \& void dump_hash(SV* hash_ref) { \& HV* hash; \& HE* hash_entry; \& int num_keys, i; \& SV* sv_key; \& SV* sv_val; \& \& if (! SvROK(hash_ref)) \& croak("hash_ref is not a reference"); \& \& hash = (HV*)SvRV(hash_ref); \& num_keys = hv_iterinit(hash); \& for (i = 0; i < num_keys; i++) { \& hash_entry = hv_iternext(hash); \& sv_key = hv_iterkeysv(hash_entry); \& sv_val = hv_iterval(hash, hash_entry); \& printf("%s => %s\en", SvPV(sv_key, PL_na), SvPV(sv_val, PL_na)); \& } \& return; \& } \& \& END_OF_C_CODE \& \& my %hash = ( \& Author => "Ingy do\*:t Net", \& Nickname => "INGY", \& Module => "Inline.pm", \& Version => "0.30", \& Language => "C", \& ); \& \& dump_hash(\e%hash); .Ve .IP "Discussion" 4 .IX Item "Discussion" The world is not made of scalars alone, although they are definitely the easiest creatures to deal with, when doing Inline stuff. Sometimes we need to deal with arrays, hashes, and code references, among other things. .Sp Since Perl subroutine calls only pass scalars as arguments, we'll need to use the argument type \f(CW\*(C`SV*\*(C'\fR and pass references to more complex types. .Sp The above program dumps the key/value pairs of a hash. To figure it out, just curl up with perlapi for a couple hours. Actually, its fairly straight forward once you are familiar with the calls. .Sp Note the \f(CW\*(C`croak\*(C'\fR function call. This is the proper way to die from your C extensions. .IP "See Also" 4 .IX Item "See Also" See perlapi for information about the Perl5 internal \s-1API.\s0 .IP "Credits" 4 .IX Item "Credits" .SS "Hash of Lists" .IX Subsection "Hash of Lists" .PD 0 .IP "Problem" 4 .IX Item "Problem" .PD .PP How do I create a Hash of Lists from C? .IP "Solution" 4 .IX Item "Solution" .Vb 2 \& use Inline C; \& use Data::Dumper; \& \& $hash_ref = load_data("./cartoon.txt"); \& print Dumper $hash_ref; \& \& _\|_END_\|_ \& _\|_C_\|_ \& \& static int next_word(char**, char*); \& \& SV* load_data(char* file_name) { \& char buffer[100], word[100], * pos; \& AV* array; \& HV* hash = newHV(); \& FILE* fh = fopen(file_name, "r"); \& \& while (fgets(pos = buffer, sizeof(buffer), fh)) { \& if (next_word(&pos, word)) { \& array = newAV(); \& hv_store(hash, word, strlen(word), \& newRV_noinc((SV*)array), 0); \& while (next_word(&pos, word)) \& av_push(array, newSVpvf("%s", word)); \& } \& } \& fclose(fh); \& return newRV_noinc((SV*) hash); \& } \& \& static int next_word(char** text_ptr, char* word) { \& char* text = *text_ptr; \& while(*text != \*(Aq\e0\*(Aq && \& *text <= \*(Aq \*(Aq) \& text++; \& if (*text <= \*(Aq \*(Aq) \& return 0; \& while(*text != \*(Aq\e0\*(Aq && \& *text > \*(Aq \*(Aq) { \& *word++ = *text++; \& } \& *word = \*(Aq\e0\*(Aq; \& *text_ptr = text; \& return 1; \& } .Ve .IP "Discussion" 4 .IX Item "Discussion" This is one of the larger recipes. But when you consider the number of calories it has, it's not so bad. The function \f(CW\*(C`load_data\*(C'\fR takes the name of a file as it's input. The file \f(CW\*(C`cartoon.text\*(C'\fR might look like: .Sp .Vb 3 \& flintstones fred barney \& jetsons george jane elroy \& simpsons homer marge bart .Ve .Sp The function will read the file, parsing each line into words. Then it will create a new hash, whereby the first word in a line becomes a hash key and the remaining words are put into an array whose reference becomes the hash value. The output looks like this: .Sp .Vb 10 \& $VAR1 = { \& \*(Aqflintstones\*(Aq => [ \& \*(Aqfred\*(Aq, \& \*(Aqbarney\*(Aq \& ], \& \*(Aqsimpsons\*(Aq => [ \& \*(Aqhomer\*(Aq, \& \*(Aqmarge\*(Aq, \& \*(Aqbart\*(Aq \& ], \& \*(Aqjetsons\*(Aq => [ \& \*(Aqgeorge\*(Aq, \& \*(Aqjane\*(Aq, \& \*(Aqelroy\*(Aq \& ] \& }; .Ve .IP "See Also" 4 .IX Item "See Also" See perlapi for information about the Perl5 internal \s-1API.\s0 .IP "Credits" 4 .IX Item "Credits" Al Danial requested a solution to this on comp.lang.perl.misc. He borrowed the idea from the \*(L"Hash of Lists\*(R" example in the Camel book. .SH "JUST DESSERTS" .IX Header "JUST DESSERTS" .SS "Win32" .IX Subsection "Win32" .IP "Problem" 4 .IX Item "Problem" How do I access Win32 DLL-s using Inline? .IP "Solution" 4 .IX Item "Solution" .Vb 2 \& use Inline C => DATA => \& LIBS => \*(Aq\-luser32\*(Aq; \& \& $text = "@ARGV" || \*(AqInline.pm works with MSWin32. Scary...\*(Aq; \& \& WinBox(\*(AqInline Text Box\*(Aq, $text); \& \& _\|_END_\|_ \& _\|_C_\|_ \& \& #include \& \& int WinBox(char* Caption, char* Text) { \& return MessageBoxA(0, Text, Caption, 0); \& } .Ve .IP "Discussion" 4 .IX Item "Discussion" This example runs on \s-1MS\s0 Windows. It makes a text box appear on the screen which contains a message of your choice. .Sp The important thing is that its proof that you can use Inline to interact with Windows DLL-s. Very scary indeed. 8\-o .Sp To use Inline on Windows with ActivePerl ( ) you'll need \s-1MS\s0 Visual Studio. You can also use the Cygwin environment, available at . .IP "See Also" 4 .IX Item "See Also" See Inline-Support for more info on MSWin32 programming with Inline. .IP "Credits" 4 .IX Item "Credits" This example was adapted from some sample code written by Garrett Goebel .SS "Embedding Perl in C" .IX Subsection "Embedding Perl in C" .IP "Problem" 4 .IX Item "Problem" How do I use Perl from a regular C program? .IP "Solution" 4 .IX Item "Solution" .Vb 1 \& #!/usr/bin/cpr \& \& int main(void) { \& printf("Using Perl version %s from a C program!\en\en", \& CPR_eval("use Config; $Config{version};")); \& \& CPR_eval("use Data::Dumper;"); \& CPR_eval("print Dumper \e\e%INC;"); \& \& return 0; \& } .Ve .IP "Discussion" 4 .IX Item "Discussion" By using \s-1CPR. \s0(C Perl Run) .Sp This example uses another Inline module, \f(CW\*(C`Inline::CPR\*(C'\fR, available separately on \s-1CPAN.\s0 When you install this module it also installs a binary interpreter called \f(CW\*(C`/usr/bin/cpr\*(C'\fR. (The path may be different on your system) .Sp When you feed a C program to the \s-1CPR\s0 interpreter, it automatically compiles and runs your code using Inline. This gives you full access to the Perl internals. \s-1CPR\s0 also provides a set of easy to use C macros for calling Perl internals. .Sp This means that you can effectively \*(L"run\*(R" C source code by putting a \s-1CPR\s0 hashbang as the first line of your C program. .IP "See Also" 4 .IX Item "See Also" See Inline::CPR for more information on using \s-1CPR.\s0 .Sp \&\f(CW\*(C`Inline::CPR\*(C'\fR can be obtained from \*(L"/search.cpan.org/search?dist=Inline\- \&\s-1CPR\*(R"\s0 in http: .IP "Credits" 4 .IX Item "Credits" Randal Schwartz , Randolph Bentson , Richard Anderson , and Tim Maher helped me figure out how to write a program that would work as a hashbang. .SH "ENTERTAINING GUESTS" .IX Header "ENTERTAINING GUESTS" As of version 0.30, Inline has the ability to work in cooperation with other modules that want to expose a C \s-1API\s0 of their own. The general syntax for doing this is: .PP .Vb 2 \& use Inline with => \*(AqModule\*(Aq; \& use Inline C => ... ; .Ve .PP This tells \f(CW\*(C`Module\*(C'\fR to pass configuration options to Inline. Options like typemaps, include paths, and external libraries, are all resolved automatically so you can just concentrate on writing the functions. .SS "Event handling with Event.pm" .IX Subsection "Event handling with Event.pm" .IP "Problem" 4 .IX Item "Problem" You need to write a C callback for the \f(CW\*(C`Event.pm\*(C'\fR module. Can this be done more easily with Inline? .IP "Solution" 4 .IX Item "Solution" .Vb 1 \& use Inline with => \*(AqEvent\*(Aq; \& \& Event\->timer(desc => \*(AqTimer #1\*(Aq, \& interval => 2, \& cb => \e&my_callback, \& ); \& \& Event\->timer(desc => \*(AqTimer #2\*(Aq, \& interval => 3, \& cb => \e&my_callback, \& ); \& \& print "Starting...\en"; \& Event::loop; \& \& use Inline C => <<\*(AqEND\*(Aq; \& void my_callback(pe_event* event) { \& pe_timer * watcher = event\->up; \& \& printf("%s\en\etEvent priority = %d\en\etWatcher priority = %d\en\en", \& SvPVX(watcher\->base.desc), \& event\->prio, \& watcher\->base.prio \& ); \& } \& END .Ve .IP "Discussion" 4 .IX Item "Discussion" The first line tells Inline to load the \f(CW\*(C`Event.pm\*(C'\fR module. Inline then queries \f(CW\*(C`Event\*(C'\fR for configuration information. It gets the name and location of Event's header files, typemaps and shared objects. The parameters that \&\f(CW\*(C`Event\*(C'\fR returns look like: .Sp .Vb 5 \& INC => "\-I $path/Event", \& TYPEMAPS => "$path/Event/typemap", \& MYEXTLIB => "$path/auto/Event/Event.$so", \& AUTO_INCLUDE => \*(Aq#include "EventAPI.h"\*(Aq, \& BOOT => \*(AqI_EVENT_API("Inline");\*(Aq, .Ve .Sp Doing all of this automatically allows you, the programmer, to simply write a function that receives a pointer of type \f(CW\*(Aqpe_event*\*(Aq\fR. This gives you access to the \f(CW\*(C`Event\*(C'\fR structure that was passed to you. .Sp In this example, I simply print values out of the structure. The Perl code defines 2 timer events which each invoke the same callback. The first one, every two seconds, and the second one, every three seconds. .Sp As of this writing, \f(CW\*(C`Event.pm\*(C'\fR is the only \s-1CPAN\s0 module that works in cooperation with Inline. .IP "See Also" 4 .IX Item "See Also" Read the \f(CW\*(C`Event.pm\*(C'\fR documentation for more information. It contains a tutorial showing several examples of using Inline with \f(CW\*(C`Event\*(C'\fR. .IP "Credits" 4 .IX Item "Credits" Jochen Stenzel originally came up with the idea of mixing Inline and \f(CW\*(C`Event\*(C'\fR. He also authored the \f(CW\*(C`Event\*(C'\fR tutorial. .Sp Joshua Pritikin is the author of \f(CW\*(C`Event.pm\*(C'\fR. .SH "FOOD FOR THOUGHT" .IX Header "FOOD FOR THOUGHT" .SS "Calling C from both Perl and C" .IX Subsection "Calling C from both Perl and C" .IP "Problem" 4 .IX Item "Problem" I'd like to be able to call the same C function from both Perl and C. Also I like to define a C function that \fBdoesn't\fR get bound to Perl. How do I do that? .IP "Solution" 4 .IX Item "Solution" .Vb 3 \& print "9 + 5 = ", add(9, 5), "\en"; \& print "SQRT(9^2 + 5^2) = ", pyth(9, 5), "\en"; \& print "9 * 5 = ", mult(9, 5), "\en"; \& \& use Inline C => <<\*(AqEND_C\*(Aq; \& int add(int x, int y) { \& return x + y; \& } \& static int mult(int x, int y) { \& return x * y; \& } \& double pyth(int x, int y) { \& return sqrt(add(mult(x, x), mult(y, y))); \& } \& END_C .Ve .IP "Discussion" 4 .IX Item "Discussion" The program produces: .Sp .Vb 3 \& 9 + 5 = 14 \& SQRT(9^2 + 5^2) = 10.295630140987 \& Can\*(Aqt locate auto/main/mult.al in @INC ... .Ve .Sp Every Inline function that is bound to Perl is also callable by C. You don't have to do anything special. Inline arranges it so that all the typemap code gets done by \s-1XS\s0 and is out of sight. By the time the C function receives control, everything has been converted from Perl to C. .Sp Of course if your function manipulates the Perl Stack, you probably don't want to call it from C (unless you \fIreally\fR know what you're doing). .Sp If you declare a function as \f(CW\*(C`static\*(C'\fR, Inline won't bind it to Perl. That's why we were able to call \f(CW\*(C`mult()\*(C'\fR from C but the call failed from Perl. .SS "Calling Perl from C" .IX Subsection "Calling Perl from C" .IP "Problem" 4 .IX Item "Problem" So now that I can call C from Perl, how do I call a Perl subroutine from an Inline C function. .IP "Solution" 4 .IX Item "Solution" .Vb 1 \& use Inline C; \& \& for(1..5) { \& c_func_1(\*(AqThis is the first line\*(Aq); \& c_func_2(\*(AqThis is the second line\*(Aq); \& print "\en"; \& } \& \& sub perl_sub_1 { \& print map "$_\en", @_; \& } \& \& _\|_DATA_\|_ \& _\|_C_\|_ \& \& void c_func_2(SV* text) { \& dSP; \& \& ENTER; \& SAVETMPS; \& \& XPUSHs(sv_2mortal(newSVpvf("Plus an extra line"))); \& PUTBACK; \& \& call_pv("perl_sub_1", G_DISCARD); \& \& FREETMPS; \& LEAVE; \& } \& \& void c_func_1(SV* text) { \& c_func_2(text); \& } .Ve .IP "Discussion" 4 .IX Item "Discussion" This demo previously made use of Inline Stack macros only \- but that's not the correct way to do it. Instead, base the callbacks on the perlcall documentation (as we're now doing). .Sp Actually, this program demonstrates calling a C function which calls another C function which in turn calls a Perl subroutine. .Sp The nice thing about Inline C functions is that you can call them from both Perl-space \fBand\fR C\-space. That's because Inline creates a wrapper function around each C function. When you use Perl to call C you're actually calling that function's wrapper. The wrapper handles typemapping and Stack management, and then calls your C function. .Sp The first time we call \f(CW\*(C`c_func_1\*(C'\fR which calls \f(CW\*(C`c_func_2\*(C'\fR. The second time we call \f(CW\*(C`c_func_2\*(C'\fR directly. \f(CW\*(C`c_func_2\*(C'\fR calls the Perl subroutine (\f(CW\*(C`perl_sub_1\*(C'\fR) using the internal \f(CW\*(C`perl_call_pv\*(C'\fR function. It has to put arguments on the stack by hand. Since there is already one argument on the stack when we enter the function, the \f(CW\*(C`XPUSHs\*(C'\fR ( which is equivalent to an \&\f(CW\*(C`Inline_Stack_Push\*(C'\fR ) adds a second argument. .Sp We iterate through a 'for' loop 5 times just to demonstrate that things still work correctly when we do that. (This was where the previous rendition, making use solely of Inline Stack macros, fell down.) .IP "See Also" 4 .IX Item "See Also" See Inline::C for more information about Stack macros. .Sp See perlapi for more information about the Perl5 internal \s-1API.\s0 .SS "Evaling C" .IX Subsection "Evaling C" .IP "Problem" 4 .IX Item "Problem" I've totally lost my marbles and I want to generate C code at run time, and \&\f(CW\*(C`eval\*(C'\fR it into Perl. How do I do this? .IP "Solution" 4 .IX Item "Solution" .Vb 2 \& use Inline; \& use Code::Generator; \& \& my $c_code = generate(\*(Aqfoo_function\*(Aq); \& \& Inline\->bind(C => $c_code); \& \& foo_function(1, 2, 3); .Ve .IP "Discussion" 4 .IX Item "Discussion" I can't think of a real life application where you would want to generate C code on the fly, but at least I know how I would do it. :) .Sp The \f(CW\*(C`bind()\*(C'\fR function of Inline let's you bind (compile\fIload\fRexecute) C functions at run time. It takes all of the same arguments as \f(CW\*(C`use Inline C => ...\*(C'\fR. .Sp The nice thing is that once a particular snippet is compiled, it remains cached so that it doesn't need to be compiled again. I can imagine that someday a mad scientist will dream up a self generating modeling system that would run faster and faster over time. .Sp If you know such a person, have them drop me a line. .SS "Providing a pure perl alternative" .IX Subsection "Providing a pure perl alternative" .IP "Problem" 4 .IX Item "Problem" I want to write a script that will use a C subroutine if Inline::C is installed, but will otherwise use an equivalent pure perl subroutine if Inline::C is not already installed. How do I do this? .IP "Solution" 4 .IX Item "Solution" .Vb 2 \& use strict; \& use warnings; \& \& eval { \& require Inline; \& Inline\->import (C => Config => \& BUILD_NOISY => 1); \& Inline\->import (C =><<\*(AqEOC\*(Aq); \& \& int foo() { \& warn("Using Inline\en"); \& return 42; \& } \& \& EOC \& }; \& \& if ($@) { \& *foo =\e&bar; \& } \& \& sub bar { \& warn("Using Pure Perl Implementation\en"); \& return 42; \& } \& \& my $x = foo(); \& print "$x\en"; .Ve .IP "Discussion" 4 .IX Item "Discussion" If Inline::C is installed and functioning properly, the C sub foo is called by the perl code. Otherwise, $@ gets set, and the equivalent pure perl function bar is instead called. .Sp Note, too, that the pure perl sub bar can still be explicitly called even if Inline::C is available. .SS "Accessing Fortran subs using Inline::C" .IX Subsection "Accessing Fortran subs using Inline::C" .IP "Problem" 4 .IX Item "Problem" I've been given a neat little sub written in fortran that takes, as its args, two integers and returns their product. And I would like to use that sub as is from Inline::C. By way of example, let's say that the fortran source file is named 'prod.f', and that it looks like this: .Sp .Vb 5 \& integer function sqarea(r,s) \& integer r, s \& sqarea = r*s \& return \& end .Ve .IP "Solution" 4 .IX Item "Solution" We can't access that code directly, but we can compile it into a library which we \fBcan\fR then access from Inline::C. Using gcc we could run: .Sp .Vb 2 \& gfortran \-c prod.f \-o prod.o \& ar cru libprod.a prod.o .Ve .Sp The function is then accessible as follows: .Sp .Vb 1 \& use warnings; \& \& use Inline C => Config => \& LIBS => \*(Aq\-L/full/path/to/libprod_location \-lprod \-lgfortran\*(Aq; \& \& use Inline C => <<\*(Aq EOC\*(Aq; \& \& int wrap_sqarea(int a, int b) { \& return sqarea_(&a, &b); \& } \& \& EOC \& \& $x = 15; \& $y = $x + 3; \& $ret = wrap_sqarea($x, $y); \& print "Product of $x and $y is $ret\en"; .Ve .IP "Discussion" 4 .IX Item "Discussion" Note firstly that, although the function is specified as 'sqarea' in the source file, gfortran appends an underscore to the name when the source is compiled. (I don't know if \fBall\fR fortran compilers do this.) Therefore Inline::C needs to call the function as 'sqarea_'. .Sp Secondly, because fortran subs pass args by reference, we need to pass the \&\fBaddresses\fR of the two integer args to \fIsqarea()\fR when we call it from our Inline::C sub. .Sp If using g77 instead of gfortran, the only necessary change is that we specify \&'\-lg2c' instead of '\-lgfortran' in our '\s-1LIBS\s0' setting. .SH "SEE ALSO" .IX Header "SEE ALSO" For generic information about Inline, see Inline. .PP For information about using Inline with C see Inline::C. .PP For information on supported languages and platforms see Inline-Support. .PP For information on writing your own Inline language support module, see Inline-API. .PP Inline's mailing list is inline@perl.org .PP To subscribe, send email to inline\-subscribe@perl.org .SH "AUTHORS" .IX Header "AUTHORS" Ingy do\*:t Net .PP Sisyphus .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" Copyright 2000\-2015. Ingy do\*:t Net. .PP Copyright 2008, 2010\-2014. Sisyphus. .PP This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. .PP See