Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / man / man3 / Inline::C-Cookbook.3
.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.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. | will give a
.\" real vertical bar. \*(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-|\(bv\*(Tr
.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" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. nr % 0
. rr F
.\}
.\"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" 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 "C-Cookbook 3"
.TH C-Cookbook 3 "2002-11-04" "perl v5.8.0" "User Contributed Perl Documentation"
.SH "NAME"
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 apdapted 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"
.Sh "Hello, world"
.IX Subsection "Hello, world"
.IP "Problem" 4
.IX Item "Problem"
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 => <<'END_C';
.Ve
.Sp
.Vb 4
\& void greet() {
\& printf("Hello, world\en");
\& }
\& END_C
.Ve
.Sp
.Vb 1
\& 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"
Brian Kernigan
.Sp
Dennis Ritchie
.Sh "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 'use Inline C=>q{void greet(){printf("Hello, world\en");}};greet'
.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 'use Inline C=>q{SV*JAxH(char*x){return newSVpvf("Just Another %s Hacker",x);}};print JAxH+Perl'
.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" <elijah@workspot.net> gave me the idea that I should
have an Inline one-liner as a signature.
.SH "Meat & Potatoes"
.IX Header "Meat & Potatoes"
.Sh "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;
.Ve
.Sp
.Vb 2
\& $filename = $ARGV[0];
\& die "Usage: perl vowels.pl filename\en" unless -f $filename;
.Ve
.Sp
.Vb 4
\& $text = join '', <>; # 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";
.Ve
.Sp
.Vb 2
\& __END__
\& __C__
.Ve
.Sp
.Vb 14
\& /* Find percentage of vowels to letters */
\& double vowel_scan(char* str) {
\& int letters = 0;
\& int vowels = 0;
\& int i = 0;
\& char c;
\& char normalize = 'a' ^ 'A';
\& /* normalize forces lower case in ASCII; upper in EBCDIC */
\& char A = normalize | 'a';
\& char E = normalize | 'e';
\& char I = normalize | 'i';
\& char O = normalize | 'o';
\& char U = normalize | 'u';
\& char Z = normalize | 'z';
.Ve
.Sp
.Vb 8
\& while(c = str[i++]) {
\& c |= normalize;
\& if (c >= A && c <= Z) {
\& letters++;
\& if (c == A || c == E || c == I || c == O || c == U)
\& vowels++;
\& }
\& }
.Ve
.Sp
.Vb 2
\& 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/dict/words
\& The letters in /usr/dict/words are 37.5% vowels.
.Ve
.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.
.Sh "Variable Argument Lists"
.IX Subsection "Variable Argument Lists"
.IP "Problem" 4
.IX Item "Problem"
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));
.Ve
.Sp
.Vb 1
\& use Inline C => <<'END_OF_C_CODE';
.Ve
.Sp
.Vb 3
\& void greet(SV* name1, ...) {
\& Inline_Stack_Vars;
\& int i;
.Ve
.Sp
.Vb 2
\& for (i = 0; i < Inline_Stack_Items; i++)
\& printf("Hello %s!\en", SvPV(Inline_Stack_Item(i), PL_na));
.Ve
.Sp
.Vb 2
\& Inline_Stack_Void;
\& }
.Ve
.Sp
.Vb 1
\& 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
.Sh "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);
.Ve
.Sp
.Vb 1
\& use Inline C => <<'END_OF_C_CODE';
.Ve
.Sp
.Vb 1
\& #include <time.h>
.Ve
.Sp
.Vb 3
\& void get_localtime(int utc) {
\& struct tm *ltime = localtime(&utc);
\& Inline_Stack_Vars;
.Ve
.Sp
.Vb 11
\& 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 <starfire@zipcon.net> contributed the original idea for
this snippet.
.Sh "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;
.Ve
.Sp
.Vb 2
\& my ($foo, $bar);
\& change($foo, $bar);
.Ve
.Sp
.Vb 2
\& print "\e$foo = $foo\en";
\& print "\e$bar = $bar\en";
.Ve
.Sp
.Vb 1
\& __C__
.Ve
.Sp
.Vb 5
\& 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 <ned@bike\-nomad.com> brought this behavior to my attention. He
also pointed out that he is not the world famous computer cyclist Steve
Roberts (http://www.microship.com), but he is close
(http://bike\-nomad.com). Thanks Ned.
.Sh "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('Ingy');
.Ve
.Sp
.Vb 1
\& use Inline C => <<'END_OF_C_CODE';
.Ve
.Sp
.Vb 3
\& SV* greeting(SV* sv_name) {
\& return (newSVpvf("Hello %s!\en", SvPV(sv_name, PL_na)));
\& }
.Ve
.Sp
.Vb 1
\& 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"
.Sh "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
.Ve
.Sp
.Vb 4
\& use CGI qw(:standard);
\& use Inline (Config =>
\& DIRECTORY => '/usr/local/apache/Inline',
\& );
.Ve
.Sp
.Vb 5
\& print (header,
\& start_html('Inline CGI Example'),
\& h1(JAxH('Inline')),
\& end_html
\& );
.Ve
.Sp
.Vb 5
\& use Inline C => <<END;
\& SV* JAxH(char* x) {
\& return newSVpvf("Just Another %s Hacker", x);
\& }
\& END
.Ve
.IP "Discussion" 4
.IX Item "Discussion"
The problem with running Inline code from a \s-1CGI\s0 script is that Inline
\&\fBwrites\fR to a build area on your disk whenever it compiles code. Most
\&\s-1CGI\s0 scripts don't (and shouldn't) be able to create a directory and
write into it.
.Sp
The solution is to explicitly tell Inline which directory to use with
the 'use Inline Config => \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"
.Sh "mod_perl"
.IX Subsection "mod_perl"
.PD 0
.IP "Problem" 4
.IX Item "Problem"
.PD
How do I use Inline with mod_perl?
.IP "Solution" 4
.IX Item "Solution"
.Vb 7
\& package Factorial;
\& use strict;
\& use Inline Config =>
\& DIRECTORY => '/usr/local/apache/Inline',
\& ENABLE => 'UNTAINT';
\& use Inline 'C';
\& Inline->init;
.Ve
.Sp
.Vb 6
\& sub handler {
\& my $r = shift;
\& $r->send_http_header('text/plain');
\& printf "%3d! = %10d\en", $_, factorial($_) for 1..100;
\& return Apache::Constants::OK;
\& }
.Ve
.Sp
.Vb 7
\& 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.
.IP "Credits" 4
.IX Item "Credits"
.Sh "Object Oriented Inline"
.IX Subsection "Object Oriented Inline"
.PD 0
.IP "Problem" 4
.IX Item "Problem"
.PD
How do I implement Object Oriented programming in Perl using C objects?
.IP "Solution" 4
.IX Item "Solution"
.Vb 3
\& my $obj1 = Soldier->new('Benjamin', 'Private', 11111);
\& my $obj2 = Soldier->new('Sanders', 'Colonel', 22222);
\& my $obj3 = Soldier->new('Matt', 'Sergeant', 33333);
.Ve
.Sp
.Vb 5
\& for my $obj ($obj1, $obj2, $obj3) {
\& print ($obj->get_serial, ") ",
\& $obj->get_name, " is a ",
\& $obj->get_rank, "\en");
\& }
.Ve
.Sp
.Vb 1
\& #---------------------------------------------------------
.Ve
.Sp
.Vb 1
\& package Soldier;
.Ve
.Sp
.Vb 1
\& use Inline C => <<'END';
.Ve
.Sp
.Vb 5
\& typedef struct {
\& char* name;
\& char* rank;
\& long serial;
\& } Soldier;
.Ve
.Sp
.Vb 4
\& SV* new(char* class, char* name, char* rank, long serial) {
\& Soldier* soldier = malloc(sizeof(Soldier));
\& SV* obj_ref = newSViv(0);
\& SV* obj = newSVrv(obj_ref, class);
.Ve
.Sp
.Vb 3
\& soldier->name = strdup(name);
\& soldier->rank = strdup(rank);
\& soldier->serial = serial;
.Ve
.Sp
.Vb 4
\& sv_setiv(obj, (IV)soldier);
\& SvREADONLY_on(obj);
\& return obj_ref;
\& }
.Ve
.Sp
.Vb 3
\& char* get_name(SV* obj) {
\& return ((Soldier*)SvIV(SvRV(obj)))->name;
\& }
.Ve
.Sp
.Vb 3
\& char* get_rank(SV* obj) {
\& return ((Soldier*)SvIV(SvRV(obj)))->rank;
\& }
.Ve
.Sp
.Vb 3
\& long get_serial(SV* obj) {
\& return ((Soldier*)SvIV(SvRV(obj)))->serial;
\& }
.Ve
.Sp
.Vb 7
\& void DESTROY(SV* obj) {
\& Soldier* soldier = (Soldier*)SvIV(SvRV(obj));
\& free(soldier->name);
\& free(soldier->rank);
\& free(soldier);
\& }
\& END
.Ve
.IP "Discussion" 4
.IX Item "Discussion"
Damian Conway has given us myriad ways of implementing \s-1OOP\s0 in Perl. This
is one he might not have thought of.
.Sp
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.
.Sp
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.
.Sp
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.
.Sp
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.
.Sp
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`strdup()\*(C'\fR. This also allocates
more memory (which we have to keep track of).
.Sp
The accessor methods are pretty straightforward. They return the current
value of their attribute.
.Sp
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.
.Sp
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"
Read \*(L"Object Oriented Perl\*(R" by Damian Conway, for more useful ways of
doing \s-1OOP\s0 in Perl.
.Sp
You can learn more Perl calls in perlapi. If you don't have Perl
5.6.0 or higher, visit http://www.perldoc.com/perl5.6/pod/perlapi.html
.IP "Credits" 4
.IX Item "Credits"
.SH "The Main Course"
.IX Header "The Main Course"
.Sh "Exposing Shared Libraries"
.IX Subsection "Exposing Shared Libraries"
.PD 0
.IP "Problem" 4
.IX Item "Problem"
.PD
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('http://www.axkit.org');
.Ve
.Sp
.Vb 3
\& use Inline C => Config =>
\& LIBS => '-lghttp';
\& use Inline C => <<'END_OF_C_CODE';
.Ve
.Sp
.Vb 1
\& #include <ghttp.h>
.Ve
.Sp
.Vb 3
\& char *get(SV* uri) {
\& SV* buffer;
\& ghttp_request* request;
.Ve
.Sp
.Vb 3
\& buffer = NEWSV(0,0);
\& request = ghttp_request_new();
\& ghttp_set_uri(request, SvPV(uri, PL_na));
.Ve
.Sp
.Vb 1
\& ghttp_set_header(request, http_hdr_Connection, "close");
.Ve
.Sp
.Vb 2
\& ghttp_prepare(request);
\& ghttp_process(request);
.Ve
.Sp
.Vb 1
\& sv_catpv(buffer, ghttp_get_body(request));
.Ve
.Sp
.Vb 1
\& ghttp_request_destroy(request);
.Ve
.Sp
.Vb 2
\& return SvPV(buffer, PL_na);
\& }
.Ve
.Sp
.Vb 1
\& END_OF_C_CODE
.Ve
.IP "Discussion" 4
.IX Item "Discussion"
This example fetches and prints the \s-1HTML\s0 from http://www.axkit.org
It requires the \s-1GNOME\s0 http libraries. http://www.gnome.org
.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 => '-lghttp';
\& use Inline C => "code ...";
.Ve
.Sp
or
.Sp
.Vb 1
\& use Inline C => "code ...", LIBS => '-lghttp';
.Ve
.Sp
To specify a specific library path, use:
.Sp
.Vb 1
\& use Inline C => "code ...", LIBS => '-L/your/lib/path -lyourlib';
.Ve
.Sp
To specify an include path use:
.Sp
.Vb 3
\& use Inline C => "code ...",
\& LIBS => '-lghttp',
\& INC => '-I/your/inc/path';
.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 <matt@sergeant.org>, author of
many \s-1CPAN\s0 modules. The configuration syntax has been modified for use
with Inline v0.30.
.Sh "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 'use Inline C => q{ double erf(double); }, ENABLE => "AUTOWRAP"; print "$_ @{[erf($_)]}" for (0..10)'
.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;
.Ve
.Sp
.Vb 4
\& use Inline C => Config =>
\& ENABLE => AUTOWRAP =>
\& LIBS => "-lreadline -lncurses -lterminfo -ltermcap ";
\& use Inline C => q{ char * readline(char *); };
.Ve
.Sp
.Vb 2
\& 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"
\&\f(CW\*(C`readline\*(C'\fR, \f(CW\*(C`Term::ReadLine::Gnu\*(C'\fR
.IP "Credits" 4
.IX Item "Credits"
\&\s-1GNU\s0 ReadLine was written by Brian Fox <bfox@ai.mit.edu> and Chet Ramey
<chet@ins.cwru.edu>. Term::ReadLine::Gnu was written by Hiroo Hayashi
<hiroo.hayashi@computer.org>. 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 <beazley@cs.uchicago.edu>.
.Sp
Ingy's inline editorial insight:
.Sp
This entire entry was contributed by Ariel Scolnicov
<ariels@compugen.co.il>. Ariel also first suggested the idea for Inline
to support function declaration processing.
.Sh "Complex Data"
.IX Subsection "Complex Data"
.IP "Problem" 4
.IX Item "Problem"
How do I deal with complex data types like hashes in Inline C?
.IP "Solution" 4
.IX Item "Solution"
.Vb 1
\& use Inline C => <<'END_OF_C_CODE';
.Ve
.Sp
.Vb 6
\& void dump_hash(SV* hash_ref) {
\& HV* hash;
\& HE* hash_entry;
\& int num_keys, i;
\& SV* sv_key;
\& SV* sv_val;
.Ve
.Sp
.Vb 2
\& if (! SvROK(hash_ref))
\& croak("hash_ref is not a reference");
.Ve
.Sp
.Vb 10
\& 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;
\& }
.Ve
.Sp
.Vb 1
\& END_OF_C_CODE
.Ve
.Sp
.Vb 7
\& my %hash = (
\& Author => "Brian Ingerson",
\& Nickname => "INGY",
\& Module => "Inline.pm",
\& Version => "0.30",
\& Language => "C",
\& );
.Ve
.Sp
.Vb 1
\& 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"
.Sh "Hash of Lists"
.IX Subsection "Hash of Lists"
.PD 0
.IP "Problem" 4
.IX Item "Problem"
.PD
How do I create a Hash of Lists from C?
.IP "Solution" 4
.IX Item "Solution"
.Vb 2
\& use Inline C;
\& use Data::Dumper;
.Ve
.Sp
.Vb 2
\& $hash_ref = load_data("./cartoon.txt");
\& print Dumper $hash_ref;
.Ve
.Sp
.Vb 2
\& __END__
\& __C__
.Ve
.Sp
.Vb 1
\& static int next_word(char**, char*);
.Ve
.Sp
.Vb 5
\& SV* load_data(char* file_name) {
\& char buffer[100], word[100], * pos;
\& AV* array;
\& HV* hash = newHV();
\& FILE* fh = fopen(file_name, "r");
.Ve
.Sp
.Vb 11
\& while (fgets(pos = buffer, sizeof(buffer), fh)) {
\& if (next_word(&pos, word)) {
\& hv_store(hash, word, strlen(word),
\& newRV_noinc((SV*)array = newAV()), 0);
\& while (next_word(&pos, word))
\& av_push(array, newSVpvf("%s", word));
\& }
\& }
\& fclose(fh);
\& return newRV_noinc((SV*) hash);
\& }
.Ve
.Sp
.Vb 15
\& static int next_word(char** text_ptr, char* word) {
\& char* text = *text_ptr;
\& while(*text != '\e0' &&
\& *text <= ' ')
\& text++;
\& if (*text <= ' ')
\& return 0;
\& while(*text != '\e0' &&
\& *text > ' ') {
\& *word++ = *text++;
\& }
\& *word = '\e0';
\& *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 16
\& $VAR1 = {
\& 'flintstones' => [
\& 'fred',
\& 'barney'
\& ],
\& 'simpsons' => [
\& 'homer',
\& 'marge',
\& 'bart'
\& ],
\& 'jetsons' => [
\& 'george',
\& 'jane',
\& 'elroy'
\& ]
\& };
.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 <alnd@pacbell.net> 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"
.Sh "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 => '-luser32';
.Ve
.Sp
.Vb 1
\& $text = "@ARGV" || 'Inline.pm works with MSWin32. Scary...';
.Ve
.Sp
.Vb 1
\& WinBox('Inline Text Box', $text);
.Ve
.Sp
.Vb 2
\& __END__
\& __C__
.Ve
.Sp
.Vb 1
\& #include <windows.h>
.Ve
.Sp
.Vb 3
\& 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 ( http://www.ActiveState.com )
you'll need \s-1MS\s0 Visual Studio. You can also use the Cygwin environment,
available at http://www.cygwin.com .
.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
<garrett@scriptpro.com>
.Sh "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
.Ve
.Sp
.Vb 1
\& int main(void) {
.Ve
.Sp
.Vb 2
\& printf("Using Perl version %s from a C program!\en\en",
\& CPR_eval("use Config; $Config{version};"));
.Ve
.Sp
.Vb 2
\& CPR_eval("use Data::Dumper;");
\& CPR_eval("print Dumper \e\e%INC;");
.Ve
.Sp
.Vb 1
\& return 0;
.Ve
.Sp
.Vb 1
\& }
.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
http://search.cpan.org/search?dist=Inline\-CPR
.IP "Credits" 4
.IX Item "Credits"
Randal Schwartz <merlyn@stonehenge.com>, Randolph Bentson
<bentson@grieg.holmsjoen.com>, Richard Anderson <starfire@zipcon.net>,
and Tim Maher <tim@consultix\-inc.com> 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 => 'Module';
\& 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.
.Sh "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 => 'Event';
.Ve
.Sp
.Vb 4
\& Event->timer(desc => 'Timer #1',
\& interval => 2,
\& cb => \e&my_callback,
\& );
.Ve
.Sp
.Vb 4
\& Event->timer(desc => 'Timer #2',
\& interval => 3,
\& cb => \e&my_callback,
\& );
.Ve
.Sp
.Vb 2
\& print "Starting...\en";
\& Event::loop;
.Ve
.Sp
.Vb 3
\& use Inline C => <<'END';
\& void my_callback(pe_event* event) {
\& pe_timer * watcher = event->up;
.Ve
.Sp
.Vb 7
\& 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 => '#include "EventAPI.h"',
\& BOOT => 'I_EVENT_API("Inline");',
.Ve
.Sp
Doing all of this automatically allows you, the programmer, to simply
write a function that receives a pointer of type \f(CW'pe_event*'\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 <perl@jochen\-stenzel.de> 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 <joshua.pritikin@db.com> is the author of \f(CW\*(C`Event.pm\*(C'\fR.
.SH "Food for Thought"
.IX Header "Food for Thought"
.Sh "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";
.Ve
.Sp
.Vb 11
\& use Inline C => <<'END_C';
\& 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't 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.
.IP "See Also" 4
.IX Item "See Also"
.PD 0
.IP "Credits" 4
.IX Item "Credits"
.PD
.Sh "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;
.Ve
.Sp
.Vb 2
\& c_func_1('This is the first line');
\& c_func_2('This is the second line');
.Ve
.Sp
.Vb 3
\& sub perl_sub_1 {
\& print map "$_\en", @_;
\& }
.Ve
.Sp
.Vb 2
\& __DATA__
\& __C__
.Ve
.Sp
.Vb 3
\& void c_func_1(SV* text) {
\& c_func_2(text);
\& }
.Ve
.Sp
.Vb 7
\& void c_func_2(SV* text) {
\& Inline_Stack_Vars;
\& Inline_Stack_Push(newSVpvf("Plus an extra line"));
\& Inline_Stack_Done;
\& perl_call_pv("main::perl_sub_1", 0);
\& Inline_Stack_Void;
\& }
.Ve
.IP "Discussion" 4
.IX Item "Discussion"
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`Inline_Stack_Push\*(C'\fR adds a
second argument. \f(CW\*(C`Inline_Stack_Void\*(C'\fR makes sure that nothing is
returned from the function.
.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.
.IP "Credits" 4
.IX Item "Credits"
.Sh "Evaling C"
.IX Subsection "Evaling C"
.PD 0
.IP "Problem" 4
.IX Item "Problem"
.PD
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;
.Ve
.Sp
.Vb 1
\& my $c_code = generate('foo_function');
.Ve
.Sp
.Vb 1
\& Inline->bind(C => $c_code);
.Ve
.Sp
.Vb 1
\& 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 know how I would do it.
:)
.Sp
The \f(CW\*(C`bind()\*(C'\fR function of Inline let's you bind (compile/load/execute) C
functions at run time. It takes all of the same arguments as 'use Inline
C => ...'.
.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.
.IP "See Also" 4
.IX Item "See Also"
.PD 0
.IP "Credits" 4
.IX Item "Credits"
.PD
.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 "AUTHOR"
.IX Header "AUTHOR"
Brian Ingerson <INGY@cpan.org>
.SH "COPYRIGHT"
.IX Header "COPYRIGHT"
Copyright (c) 2001, 2002, Brian Ingerson.
.PP
All Rights Reserved. This module is free software. It may be
used, redistributed and/or modified under the terms of the Perl
Artistic License.
.PP
See http://www.perl.com/perl/misc/Artistic.html