SlideShare uma empresa Scribd logo
1 de 21
Embedding Perl in C and
 the other way around




      Marian Marinov(mm@1h.com
                  
            Co-Founder and CIO of 1H Ltd.
Embedding C in Perl




              
The XS way...

       It cannot be seen, cannot be felt,
     Cannot be heard, cannot be smelt.
    It lies behind stars and under hills,
             And empty holes it fills.
                  - J.R.R. Tolkien, The Hobbit


    Answer: dark.

                         
XS Docs

● perlman:perlxstut
● man perlxs

● man perlguts

● man perlapi

● man h2xs




                       
XS Basics
● SV – Scalar Value                 SV*   newSVsv(SV*);
● AV  – Array Value
● HV  – Hash Value
● IV  – Integer Value               SV*   newSViv(IV);
● UV  – Unsigned Integer Value      SV*   newSVuv(UV);
● NV  – Double Value                SV*   newSVnv(double);
● PV  – String Value
●SV* newSVpv(const char*, STRLEN);

●SV* newSVpvn(const char*, STRLEN);

●SV* newSVpvf(const char*, ...);




    SvIV(SV*)
    SvUV(SV*)
    SvNV(SV*)
    SvPV(SV*, STRLEN len)
    SvPV_nolen(SV*)
                                
Inline::C
$ cat inline.pl
#!/usr/bin/perl
use Inline C=>'
void some_func() {
        printf("Hello Worldn");
}';
&some_func

$ ./inline.pl
Hello World

Examples from Inline::C-Cookbook
                     
fun way of using Inline::C

$ cat perl­sign.pl 
#!/usr/bin/perl 
use Inline C=>'
void C() {
    int m,u,e=0;float l,_,I;
    for(;1840­e;putchar((++e>907&&942>e?61­m:u)
["n)moc.isc@rezneumb(rezneuM drahnreB"]))
        for(u=_=l=0;79­(m=e%80)&&I*l+_*_<6&&26­+
+u;_=2*l*_+e/80*.09­1,l=I)
            I=l*l­_*_­2+m/27.;
    }';
&C
                             
mmmmmmmmooooooooooooooooooooooooocccccccccc....is@zrre i.cccccccoooooooooommmmm
mmmmmmoooooooooooooooooooooooccccccccccc.....iiscrr n@csi...ccccccoooooooooommm
mmmmooooooooooooooooooooooccccccccccc....iiiss@n     zMesii....cccccoooooooooom
mmooooooooooooooooooooocccccccccc....iisssssc@rn      erccsiiiii..ccccooooooooo
moooooooooooooooooocccccccc.......iis@e uMeu r          e r@@@ezs..cccoooooooo
oooooooooooooooccccccc.........iiiisc@z                     e   eci..cccooooooo
ooooooooooccccccc..iiiiiiiiiiiiisscz z                         z@sii.ccccoooooo
oooooccccccccc...iicz@ccccz@ccccccrrr                              s..cccoooooo
ooocccccccc.....iisc@eb     bnneree                              eci..ccccooooo
occcccccc.....iisccrnb           m                               nci..ccccooooo
ccc....iiiiisss@emee(                                            cii..cccccoooo
iscc@@beremeene(           Bernhard Muenzer(bmuenzer@csi.com) ercsi...cccccoooo
c....iiiiiisssc@e rnz                                           esi...cccccoooo
occccccc....iiiscc@rb            (                               esi..ccccooooo
oocccccccc......iisc@z        bneze                              z@i..ccccooooo
ooooocccccccc....ii@er@@@@nr@cccc@e                               es..cccoooooo
oooooooooccccccc...@siiiiiiiiisssscnM                          urcsi..cccoooooo
ooooooooooooooccccccc..........iiiisc@e                         zsi..cccooooooo
mooooooooooooooooocccccccc.......iiis@    nu               er eznri.cccoooooooo
mmoooooooooooooooooooocccccccccc....issc@ccc@@rn      er@cssiiiss..cccooooooooo
mmmmoooooooooooooooooooooccccccccccc....iiiisc@z      rrsii.....ccccoooooooooom
mmmmmooooooooooooooooooooooocccccccccccc....iis@rz rrcsi....ccccccoooooooooomm
mmmmmmmmoooooooooooooooooooooooocccccccccc....iisceeeusi..cccccccooooooooommmmm

                                         
Multiple Return Values

print map {"$_n"} get_localtime(time);

use Inline C => <<'END_OF_C_CODE';

#include <time.h>
void get_localtime(int 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
Variable Argument Lists


greet(qw(Sarathy Jan Sparky Murray Mike));

use Inline C => <<'END_OF_C_CODE';
void greet(SV* name1, ...) {
  Inline_Stack_Vars;
  int i;

  for (i = 0; i < Inline_Stack_Items; i++)
    printf("Hello %s!n",
       SvPV(Inline_Stack_Item(i), PL_na));

  Inline_Stack_Void;
}
END_OF_C_CODE
                         
Another way of using Inline::C


use Inline C;

$vp = string_scan($text);      # call our function

__END__
__C__
/*
 * Our C code goes here
 */
int string_scan(char* str) {

}
                         
Embedding Perl in C




              
How you can do it?


● ExtUtils::Embed
      perl -MExtUtils::Embed -e ccopts -e ldopts
● B::C

● The only way... XS




                          
Docs


man   perlembed
man   perlcall
man   perlguts
man   perlapi
man   perlxs



                    
B::C/perlcc
●   Works with Perl 5.6.0
●   Works with Perl 5.13.x

#!/usr/bin/perl
use strict;
use warnings;
use lib '.';
use parse_config;

my $a = 'some text';
my $b = 13;
my %config = parse_config('/etc/guardian.conf');
#my %config = ( df => 13, hj => 18);
printf "%s %dn", $a, $b;
while (my ($k,$v) = each %config) {
        print "$k :: $vn";
}
                                 
$ perlcc -o em em.pl
$ ./em
Segmentation fault

$ perlcc -o em em.pl
$ ./em
some text 13
df :: 13
hj :: 18




                        
#include "embed.h"

int main (int argc, char **argv, char **env) {
        char *embedding[] = { "", "-e", "0" };
        unsigned char *perlPlain;
        size_t len = 0;
        int err = 0;

        PERL_SYS_INIT3(&argc,&argv,&env);
        my_perl = perl_alloc();
        perl_construct( my_perl );

        perl_parse(my_perl, xs_init, 3, embedding, NULL);
        PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
        perl_run(my_perl);

        perlPlain=spc_base64_decode(&perl64,&len,0,&err);
        eval_pv(perlPlain, TRUE);

        perl_destruct(my_perl);
        perl_free(my_perl);
        PERL_SYS_TERM();
        return 0;
                                   
}
#ifndef _EMBED_H
#define _EMBED_H
#include <EXTERN.h>
#include <perl.h>
#include "base64.h"
#include "code_64.h"

static PerlInterpreter *my_perl;
static void xs_init (pTHX);

EXTERN_C void boot_DynaLoader (pTHX_ CV* cv);
EXTERN_C void boot_Socket (pTHX_ CV* cv);
EXTERN_C void xs_init(pTHX) {
        char *file = __FILE__;
        /* DynaLoader is a special case */
        newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader,
file);
}

#endif

                                    
$ ./embed --version

This is perl, v5.10.1 (*) built for i386-linux-thread-multi

Copyright 1987-2009, Larry Wall

Perl may be copied only under the terms of either the Artistic
License or the
GNU General Public License, which may be found in the Perl 5
source kit.

Complete documentation for Perl, including FAQ lists, should be
found on
this system using "man perl" or "perldoc perl". If you have
access to the
Internet, point your browser at http://www.perl.org/, the Perl
Home Page.



                                   
# perl -MExtUtils::Embed -e ccopts -e ldopts
-Wl,-E -Wl,-rpath,/usr/lib/perl5/5.8.8/i386-linux-thread-
multi/CORE -L/usr/local/lib /usr/lib/perl5/5.8.8/i386-linux-
thread-multi/auto/DynaLoader/DynaLoader.a
-L/usr/lib/perl5/5.8.8/i386-linux-thread-multi/CORE -lperl
-lresolv -lnsl -ldl -lm -lcrypt -lutil -lpthread -lc
 -D_REENTRANT -D_GNU_SOURCE -fno-strict-aliasing -pipe
-Wdeclaration-after-statement -I/usr/local/include
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/usr/include/gdbm
-I/usr/lib/perl5/5.8.8/i386-linux-thread-multi/CORE

# gcc -o embed embed.c $(perl -MExtUtils::Embed -e ccopts -e
ldopts)




                                 
call_argv("showtime", G_DISCARD | G_NOARGS, args);

                             vs.

      eval_pv(perlPlain, TRUE);


    /** Treat $a as an integer **/
      eval_pv("$a = 3; $a **= 2", TRUE);
      printf("a = %dn", SvIV(get_sv("a", 0)));

    /** Treat $a as a float **/
      eval_pv("$a = 3.14; $a **= 2", TRUE);
      printf("a = %fn", SvNV(get_sv("a", 0)));

 /** Treat $a as a string **/
   eval_pv("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);",
TRUE);
   printf("a = %sn", SvPV_nolen(get_sv("a", 0)));

                                    

Mais conteúdo relacionado

Mais procurados

Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Kevlin Henney
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Benjamin Bock
 
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...festival ICT 2016
 
ATS language overview
ATS language overviewATS language overview
ATS language overviewKiwamu Okabe
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameAndrey Karpov
 
how to hack with pack and unpack
how to hack with pack and unpackhow to hack with pack and unpack
how to hack with pack and unpackDavid Lowe
 
R で解く FizzBuzz 問題
R で解く FizzBuzz 問題R で解く FizzBuzz 問題
R で解く FizzBuzz 問題Kosei ABE
 
Code obfuscation, php shells & more
Code obfuscation, php shells & moreCode obfuscation, php shells & more
Code obfuscation, php shells & moreMattias Geniar
 
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...Patrick Niedzielski
 
An Introduction to PHP Dependency Management With Composer
An Introduction to PHP Dependency Management With ComposerAn Introduction to PHP Dependency Management With Composer
An Introduction to PHP Dependency Management With ComposerOomph, Inc.
 
Office doc (10)
Office doc (10)Office doc (10)
Office doc (10)ly2wf
 
Search and Replacement Techniques in Emacs: avy, swiper, multiple-cursor, ag,...
Search and Replacement Techniques in Emacs: avy, swiper, multiple-cursor, ag,...Search and Replacement Techniques in Emacs: avy, swiper, multiple-cursor, ag,...
Search and Replacement Techniques in Emacs: avy, swiper, multiple-cursor, ag,...Kazuki Yoshida
 
Combine vs RxSwift
Combine vs RxSwiftCombine vs RxSwift
Combine vs RxSwiftshark-sea
 
[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And PortKeiichi Daiba
 
망고100 보드로 놀아보자 7
망고100 보드로 놀아보자 7망고100 보드로 놀아보자 7
망고100 보드로 놀아보자 7종인 전
 
Dip Your Toes in the Sea of Security (PHP MiNDS January Meetup 2016)
Dip Your Toes in the Sea of Security (PHP MiNDS January Meetup 2016)Dip Your Toes in the Sea of Security (PHP MiNDS January Meetup 2016)
Dip Your Toes in the Sea of Security (PHP MiNDS January Meetup 2016)James Titcumb
 

Mais procurados (20)

FizzBuzz Trek
FizzBuzz TrekFizzBuzz Trek
FizzBuzz Trek
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
 
Get Kata
Get KataGet Kata
Get Kata
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...
 
ATS language overview
ATS language overviewATS language overview
ATS language overview
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto Game
 
how to hack with pack and unpack
how to hack with pack and unpackhow to hack with pack and unpack
how to hack with pack and unpack
 
gemdiff
gemdiffgemdiff
gemdiff
 
R で解く FizzBuzz 問題
R で解く FizzBuzz 問題R で解く FizzBuzz 問題
R で解く FizzBuzz 問題
 
ES6 - Level up your JavaScript Skills
ES6 - Level up your JavaScript SkillsES6 - Level up your JavaScript Skills
ES6 - Level up your JavaScript Skills
 
Code obfuscation, php shells & more
Code obfuscation, php shells & moreCode obfuscation, php shells & more
Code obfuscation, php shells & more
 
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...
 
An Introduction to PHP Dependency Management With Composer
An Introduction to PHP Dependency Management With ComposerAn Introduction to PHP Dependency Management With Composer
An Introduction to PHP Dependency Management With Composer
 
Office doc (10)
Office doc (10)Office doc (10)
Office doc (10)
 
Search and Replacement Techniques in Emacs: avy, swiper, multiple-cursor, ag,...
Search and Replacement Techniques in Emacs: avy, swiper, multiple-cursor, ag,...Search and Replacement Techniques in Emacs: avy, swiper, multiple-cursor, ag,...
Search and Replacement Techniques in Emacs: avy, swiper, multiple-cursor, ag,...
 
Combine vs RxSwift
Combine vs RxSwiftCombine vs RxSwift
Combine vs RxSwift
 
[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port
 
망고100 보드로 놀아보자 7
망고100 보드로 놀아보자 7망고100 보드로 놀아보자 7
망고100 보드로 놀아보자 7
 
Dip Your Toes in the Sea of Security (PHP MiNDS January Meetup 2016)
Dip Your Toes in the Sea of Security (PHP MiNDS January Meetup 2016)Dip Your Toes in the Sea of Security (PHP MiNDS January Meetup 2016)
Dip Your Toes in the Sea of Security (PHP MiNDS January Meetup 2016)
 

Semelhante a Embedding Perl in C and the other way around

start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()Kiwamu Okabe
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlHideaki Ohno
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
 
The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)Mike Friedman
 
Im trying to run make qemu-nox In a putty terminal but it.pdf
Im trying to run  make qemu-nox  In a putty terminal but it.pdfIm trying to run  make qemu-nox  In a putty terminal but it.pdf
Im trying to run make qemu-nox In a putty terminal but it.pdfmaheshkumar12354
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfezonesolutions
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Yandex
 
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataKernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataAnne Nicolas
 
NativeBoost
NativeBoostNativeBoost
NativeBoostESUG
 
Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)ujihisa
 
(Slightly) Smarter Smart Pointers
(Slightly) Smarter Smart Pointers(Slightly) Smarter Smart Pointers
(Slightly) Smarter Smart PointersCarlo Pescio
 
Introduction to Compiler Development
Introduction to Compiler DevelopmentIntroduction to Compiler Development
Introduction to Compiler DevelopmentLogan Chien
 
Unit 4
Unit 4Unit 4
Unit 4siddr
 
Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisaujihisa
 
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);Joel Porquet
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321Teddy Hsiung
 

Semelhante a Embedding Perl in C and the other way around (20)

C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed Perl
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)
 
Im trying to run make qemu-nox In a putty terminal but it.pdf
Im trying to run  make qemu-nox  In a putty terminal but it.pdfIm trying to run  make qemu-nox  In a putty terminal but it.pdf
Im trying to run make qemu-nox In a putty terminal but it.pdf
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataKernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
 
Quiz 9
Quiz 9Quiz 9
Quiz 9
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)
 
(Slightly) Smarter Smart Pointers
(Slightly) Smarter Smart Pointers(Slightly) Smarter Smart Pointers
(Slightly) Smarter Smart Pointers
 
Introduction to Compiler Development
Introduction to Compiler DevelopmentIntroduction to Compiler Development
Introduction to Compiler Development
 
Unit 4
Unit 4Unit 4
Unit 4
 
Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisa
 
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
 
Message in a bottle
Message in a bottleMessage in a bottle
Message in a bottle
 

Mais de Marian Marinov

Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingMarian Marinov
 
Basic presentation of cryptography mechanisms
Basic presentation of cryptography mechanismsBasic presentation of cryptography mechanisms
Basic presentation of cryptography mechanismsMarian Marinov
 
Microservices: Benefits, drawbacks and are they for me?
Microservices: Benefits, drawbacks and are they for me?Microservices: Benefits, drawbacks and are they for me?
Microservices: Benefits, drawbacks and are they for me?Marian Marinov
 
Introduction and replication to DragonflyDB
Introduction and replication to DragonflyDBIntroduction and replication to DragonflyDB
Introduction and replication to DragonflyDBMarian Marinov
 
Message Queuing - Gearman, Mosquitto, Kafka and RabbitMQ
Message Queuing - Gearman, Mosquitto, Kafka and RabbitMQMessage Queuing - Gearman, Mosquitto, Kafka and RabbitMQ
Message Queuing - Gearman, Mosquitto, Kafka and RabbitMQMarian Marinov
 
How to successfully migrate to DevOps .pdf
How to successfully migrate to DevOps .pdfHow to successfully migrate to DevOps .pdf
How to successfully migrate to DevOps .pdfMarian Marinov
 
How to survive in the work from home era
How to survive in the work from home eraHow to survive in the work from home era
How to survive in the work from home eraMarian Marinov
 
Improve your storage with bcachefs
Improve your storage with bcachefsImprove your storage with bcachefs
Improve your storage with bcachefsMarian Marinov
 
Control your service resources with systemd
 Control your service resources with systemd  Control your service resources with systemd
Control your service resources with systemd Marian Marinov
 
Comparison of-foss-distributed-storage
Comparison of-foss-distributed-storageComparison of-foss-distributed-storage
Comparison of-foss-distributed-storageMarian Marinov
 
Защо и как да обогатяваме знанията си?
Защо и как да обогатяваме знанията си?Защо и как да обогатяваме знанията си?
Защо и как да обогатяваме знанията си?Marian Marinov
 
Securing your MySQL server
Securing your MySQL serverSecuring your MySQL server
Securing your MySQL serverMarian Marinov
 
DoS and DDoS mitigations with eBPF, XDP and DPDK
DoS and DDoS mitigations with eBPF, XDP and DPDKDoS and DDoS mitigations with eBPF, XDP and DPDK
DoS and DDoS mitigations with eBPF, XDP and DPDKMarian Marinov
 
Challenges with high density networks
Challenges with high density networksChallenges with high density networks
Challenges with high density networksMarian Marinov
 
SiteGround building automation
SiteGround building automationSiteGround building automation
SiteGround building automationMarian Marinov
 
Preventing cpu side channel attacks with kernel tracking
Preventing cpu side channel attacks with kernel trackingPreventing cpu side channel attacks with kernel tracking
Preventing cpu side channel attacks with kernel trackingMarian Marinov
 
Managing a lot of servers
Managing a lot of serversManaging a lot of servers
Managing a lot of serversMarian Marinov
 
Let's Encrypt failures
Let's Encrypt failuresLet's Encrypt failures
Let's Encrypt failuresMarian Marinov
 

Mais de Marian Marinov (20)

Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & Logging
 
Basic presentation of cryptography mechanisms
Basic presentation of cryptography mechanismsBasic presentation of cryptography mechanisms
Basic presentation of cryptography mechanisms
 
Microservices: Benefits, drawbacks and are they for me?
Microservices: Benefits, drawbacks and are they for me?Microservices: Benefits, drawbacks and are they for me?
Microservices: Benefits, drawbacks and are they for me?
 
Introduction and replication to DragonflyDB
Introduction and replication to DragonflyDBIntroduction and replication to DragonflyDB
Introduction and replication to DragonflyDB
 
Message Queuing - Gearman, Mosquitto, Kafka and RabbitMQ
Message Queuing - Gearman, Mosquitto, Kafka and RabbitMQMessage Queuing - Gearman, Mosquitto, Kafka and RabbitMQ
Message Queuing - Gearman, Mosquitto, Kafka and RabbitMQ
 
How to successfully migrate to DevOps .pdf
How to successfully migrate to DevOps .pdfHow to successfully migrate to DevOps .pdf
How to successfully migrate to DevOps .pdf
 
How to survive in the work from home era
How to survive in the work from home eraHow to survive in the work from home era
How to survive in the work from home era
 
Managing sysadmins
Managing sysadminsManaging sysadmins
Managing sysadmins
 
Improve your storage with bcachefs
Improve your storage with bcachefsImprove your storage with bcachefs
Improve your storage with bcachefs
 
Control your service resources with systemd
 Control your service resources with systemd  Control your service resources with systemd
Control your service resources with systemd
 
Comparison of-foss-distributed-storage
Comparison of-foss-distributed-storageComparison of-foss-distributed-storage
Comparison of-foss-distributed-storage
 
Защо и как да обогатяваме знанията си?
Защо и как да обогатяваме знанията си?Защо и как да обогатяваме знанията си?
Защо и как да обогатяваме знанията си?
 
Securing your MySQL server
Securing your MySQL serverSecuring your MySQL server
Securing your MySQL server
 
Sysadmin vs. dev ops
Sysadmin vs. dev opsSysadmin vs. dev ops
Sysadmin vs. dev ops
 
DoS and DDoS mitigations with eBPF, XDP and DPDK
DoS and DDoS mitigations with eBPF, XDP and DPDKDoS and DDoS mitigations with eBPF, XDP and DPDK
DoS and DDoS mitigations with eBPF, XDP and DPDK
 
Challenges with high density networks
Challenges with high density networksChallenges with high density networks
Challenges with high density networks
 
SiteGround building automation
SiteGround building automationSiteGround building automation
SiteGround building automation
 
Preventing cpu side channel attacks with kernel tracking
Preventing cpu side channel attacks with kernel trackingPreventing cpu side channel attacks with kernel tracking
Preventing cpu side channel attacks with kernel tracking
 
Managing a lot of servers
Managing a lot of serversManaging a lot of servers
Managing a lot of servers
 
Let's Encrypt failures
Let's Encrypt failuresLet's Encrypt failures
Let's Encrypt failures
 

Último

Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 

Último (20)

Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 

Embedding Perl in C and the other way around

  • 1. Embedding Perl in C and the other way around   Marian Marinov(mm@1h.com   Co-Founder and CIO of 1H Ltd.
  • 3. The XS way... It cannot be seen, cannot be felt, Cannot be heard, cannot be smelt. It lies behind stars and under hills, And empty holes it fills. - J.R.R. Tolkien, The Hobbit Answer: dark.    
  • 4. XS Docs ● perlman:perlxstut ● man perlxs ● man perlguts ● man perlapi ● man h2xs    
  • 5. XS Basics ● SV – Scalar Value SV* newSVsv(SV*); ● AV – Array Value ● HV – Hash Value ● IV – Integer Value SV* newSViv(IV); ● UV – Unsigned Integer Value SV* newSVuv(UV); ● NV – Double Value SV* newSVnv(double); ● PV – String Value ●SV* newSVpv(const char*, STRLEN); ●SV* newSVpvn(const char*, STRLEN); ●SV* newSVpvf(const char*, ...); SvIV(SV*) SvUV(SV*) SvNV(SV*) SvPV(SV*, STRLEN len) SvPV_nolen(SV*)    
  • 6. Inline::C $ cat inline.pl #!/usr/bin/perl use Inline C=>' void some_func() { printf("Hello Worldn"); }'; &some_func $ ./inline.pl Hello World Examples from Inline::C-Cookbook    
  • 7. fun way of using Inline::C $ cat perl­sign.pl  #!/usr/bin/perl  use Inline C=>' void C() { int m,u,e=0;float l,_,I; for(;1840­e;putchar((++e>907&&942>e?61­m:u) ["n)moc.isc@rezneumb(rezneuM drahnreB"])) for(u=_=l=0;79­(m=e%80)&&I*l+_*_<6&&26­+ +u;_=2*l*_+e/80*.09­1,l=I) I=l*l­_*_­2+m/27.; }'; &C    
  • 8. mmmmmmmmooooooooooooooooooooooooocccccccccc....is@zrre i.cccccccoooooooooommmmm mmmmmmoooooooooooooooooooooooccccccccccc.....iiscrr n@csi...ccccccoooooooooommm mmmmooooooooooooooooooooooccccccccccc....iiiss@n zMesii....cccccoooooooooom mmooooooooooooooooooooocccccccccc....iisssssc@rn erccsiiiii..ccccooooooooo moooooooooooooooooocccccccc.......iis@e uMeu r e r@@@ezs..cccoooooooo oooooooooooooooccccccc.........iiiisc@z e eci..cccooooooo ooooooooooccccccc..iiiiiiiiiiiiisscz z z@sii.ccccoooooo oooooccccccccc...iicz@ccccz@ccccccrrr s..cccoooooo ooocccccccc.....iisc@eb bnneree eci..ccccooooo occcccccc.....iisccrnb m nci..ccccooooo ccc....iiiiisss@emee( cii..cccccoooo iscc@@beremeene( Bernhard Muenzer(bmuenzer@csi.com) ercsi...cccccoooo c....iiiiiisssc@e rnz esi...cccccoooo occccccc....iiiscc@rb ( esi..ccccooooo oocccccccc......iisc@z bneze z@i..ccccooooo ooooocccccccc....ii@er@@@@nr@cccc@e es..cccoooooo oooooooooccccccc...@siiiiiiiiisssscnM urcsi..cccoooooo ooooooooooooooccccccc..........iiiisc@e zsi..cccooooooo mooooooooooooooooocccccccc.......iiis@ nu er eznri.cccoooooooo mmoooooooooooooooooooocccccccccc....issc@ccc@@rn er@cssiiiss..cccooooooooo mmmmoooooooooooooooooooooccccccccccc....iiiisc@z rrsii.....ccccoooooooooom mmmmmooooooooooooooooooooooocccccccccccc....iis@rz rrcsi....ccccccoooooooooomm mmmmmmmmoooooooooooooooooooooooocccccccccc....iisceeeusi..cccccccooooooooommmmm    
  • 9. Multiple Return Values print map {"$_n"} get_localtime(time); use Inline C => <<'END_OF_C_CODE'; #include <time.h> void get_localtime(int 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
  • 10. Variable Argument Lists greet(qw(Sarathy Jan Sparky Murray Mike)); use Inline C => <<'END_OF_C_CODE'; void greet(SV* name1, ...) { Inline_Stack_Vars; int i; for (i = 0; i < Inline_Stack_Items; i++) printf("Hello %s!n", SvPV(Inline_Stack_Item(i), PL_na)); Inline_Stack_Void; } END_OF_C_CODE    
  • 11. Another way of using Inline::C use Inline C; $vp = string_scan($text); # call our function __END__ __C__ /* * Our C code goes here */ int string_scan(char* str) { }    
  • 13. How you can do it? ● ExtUtils::Embed perl -MExtUtils::Embed -e ccopts -e ldopts ● B::C ● The only way... XS    
  • 14. Docs man perlembed man perlcall man perlguts man perlapi man perlxs    
  • 15. B::C/perlcc ● Works with Perl 5.6.0 ● Works with Perl 5.13.x #!/usr/bin/perl use strict; use warnings; use lib '.'; use parse_config; my $a = 'some text'; my $b = 13; my %config = parse_config('/etc/guardian.conf'); #my %config = ( df => 13, hj => 18); printf "%s %dn", $a, $b; while (my ($k,$v) = each %config) { print "$k :: $vn"; }    
  • 16. $ perlcc -o em em.pl $ ./em Segmentation fault $ perlcc -o em em.pl $ ./em some text 13 df :: 13 hj :: 18    
  • 17. #include "embed.h" int main (int argc, char **argv, char **env) { char *embedding[] = { "", "-e", "0" }; unsigned char *perlPlain; size_t len = 0; int err = 0; PERL_SYS_INIT3(&argc,&argv,&env); my_perl = perl_alloc(); perl_construct( my_perl ); perl_parse(my_perl, xs_init, 3, embedding, NULL); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; perl_run(my_perl); perlPlain=spc_base64_decode(&perl64,&len,0,&err); eval_pv(perlPlain, TRUE); perl_destruct(my_perl); perl_free(my_perl); PERL_SYS_TERM(); return 0;     }
  • 18. #ifndef _EMBED_H #define _EMBED_H #include <EXTERN.h> #include <perl.h> #include "base64.h" #include "code_64.h" static PerlInterpreter *my_perl; static void xs_init (pTHX); EXTERN_C void boot_DynaLoader (pTHX_ CV* cv); EXTERN_C void boot_Socket (pTHX_ CV* cv); EXTERN_C void xs_init(pTHX) { char *file = __FILE__; /* DynaLoader is a special case */ newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file); } #endif    
  • 19. $ ./embed --version This is perl, v5.10.1 (*) built for i386-linux-thread-multi Copyright 1987-2009, Larry Wall Perl may be copied only under the terms of either the Artistic License or the GNU General Public License, which may be found in the Perl 5 source kit. Complete documentation for Perl, including FAQ lists, should be found on this system using "man perl" or "perldoc perl". If you have access to the Internet, point your browser at http://www.perl.org/, the Perl Home Page.    
  • 20. # perl -MExtUtils::Embed -e ccopts -e ldopts -Wl,-E -Wl,-rpath,/usr/lib/perl5/5.8.8/i386-linux-thread- multi/CORE -L/usr/local/lib /usr/lib/perl5/5.8.8/i386-linux- thread-multi/auto/DynaLoader/DynaLoader.a -L/usr/lib/perl5/5.8.8/i386-linux-thread-multi/CORE -lperl -lresolv -lnsl -ldl -lm -lcrypt -lutil -lpthread -lc -D_REENTRANT -D_GNU_SOURCE -fno-strict-aliasing -pipe -Wdeclaration-after-statement -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/usr/include/gdbm -I/usr/lib/perl5/5.8.8/i386-linux-thread-multi/CORE # gcc -o embed embed.c $(perl -MExtUtils::Embed -e ccopts -e ldopts)    
  • 21. call_argv("showtime", G_DISCARD | G_NOARGS, args); vs. eval_pv(perlPlain, TRUE); /** Treat $a as an integer **/ eval_pv("$a = 3; $a **= 2", TRUE); printf("a = %dn", SvIV(get_sv("a", 0))); /** Treat $a as a float **/ eval_pv("$a = 3.14; $a **= 2", TRUE); printf("a = %fn", SvNV(get_sv("a", 0))); /** Treat $a as a string **/ eval_pv("$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE); printf("a = %sn", SvPV_nolen(get_sv("a", 0)));    

Notas do Editor

  1. Why would I want to do that? Get some performance by using native C for some of the processing Embed parts of your existing C application into your Perl app without rewriting it completely
  2. XS is an interface description file format used to create an extension interface between Perl and C code extremely hard to learn even the smallest program must be implemented as additional module There is another, similar way using SWIG... I don&apos;t know how it works :( If someone is interested... www.swig.org
  3. .
  4. Scalar, Hash and Arrays are typedefs which can include any of the following types. You create the value with the coresponding newSV* function. You access the value with the coresponding Sv* function.
  5. Describe the way we add and execute the C code.
  6. Describe the way we add and execute the code. We begin the function with Inline_Stack_Vars This defines some internal variables including Inline_Stack_Items Inline_Stack_* variables can be used only when we use ... in the argument list or the return type of the function is VOID. sv_2mortal() – marks a variable as ready for destroy newSViv() - creates a Scalar Value from integer
  7. We begin the function with Inline_Stack_Vars This defines some internal variables including Inline_Stack_Items Inline_Stack_* variables can be used only when we use ... in the argument list or the return type of the function is VOID. We have to have at least one argument before the variable length argument because of the XS parsing.
  8. We begin the function with Inline_Stack_Vars This defines some internal variables including Inline_Stack_Items Inline_Stack_* variables can be used only when we use ... in the argument list or the return type of the function is VOID. We have to have at least one argument before the variable length argument because of the XS parsing.
  9. Why would I want to do that? Use Perl&apos;s RE Package your software into a single binary Use some of the nice Perl already working perl modules in your C application
  10. In all cases ExtUtils::Embed will help with the compilation flags. B::C is used for direct compile (perlcc) but is available only for perl 5.8.0 or 5.13.x. Using XS seams the only portable/compatible way...
  11. it should work with perl &gt;=5.10 but i haven&apos;t made it to work :(