unlinker has asked for the wisdom of the Perl Monks concerning the following question:
I am starting a personal project to build a Perl API for a C library whose source is not available but headers and the shared library are. After some good advice here, and some largely unsuccessful attempts at understanding the XS docs, I have decided to begin from a simpler starting point - Inline::C and then re-attempt XS once I understand perlguts and the perlapi better. I want to reach that better understanding in 3 steps:
At the end of it I am hoping to be able to write a tutorial for others like me. I am currently at the middle of Step 1 and using perldoc: perlguts as a guide. Based on this, I have written a few baby programs and I wanted to post them here and then follow them up with questions for the wise monks here around this code. First, here is a toy program that creates a string for perl to print:
#!/usr/bin/perl use Inline C; use strict; use warnings; print mkstr() . "\n"; __END__ __C__ SV* mkstr() { return newSVpv("This is another string!", 0); }
Here is a program to create an array in C and use it in perl:
#!/usr/bin/perl use Inline C; use strict; use warnings; use Data::Dumper; my $arr = mkarr(); print ref($arr) . "\n"; print Dumper($arr) . "\n"; __END__ __C__ AV* mkarr() { int i; int size = 10; SV** pint = (SV **) malloc(size * sizeof(SV*)); for(i = 0; i < size; ++i) pint[i] = newSViv(i); return av_make(size, pint); }
Here is one that creates a hash for perl to handle:
#!/usr/bin/perl use Inline C; use strict; use warnings; use Data::Dumper; my $hash = mkhash(); print ref($hash) . "\n"; print Dumper($hash) . "\n"; __END__ __C__ HV* mkhash() { HV *hash = newHV(); hv_store(hash, "name", 5, newSVpv("John Doe", 0), 0); hv_store(hash, "age", 4, newSViv(42), 0); return hash; }
Here is a program that blesses that hash in a Class:
#!/usr/bin/perl use Inline C; use strict; use warnings; use Data::Dumper; my $obj = mkobj(); print ref($obj) . "\n"; print Dumper($obj) . "\n"; __END__ __C__ SV* mkobj() { HV* hash = newHV(); hv_store(hash, "name", 5, newSVpv("John Doe", 0), 0); hv_store(hash, "age", 4, newSViv(42), 0); SV* rv = newRV_inc((SV*) hash); return sv_bless(rv, gv_stashpv("MyClass", GV_ADD)); }
And now for a few questions around the various baby-code above:
SV* newRV_inc((SV*) thing);and others mentioned in perlguts
Would really appreciate your answers and your advice. Thank you
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: A few very basic questions about Extending Perl
by cdarke (Prior) on Dec 26, 2010 at 16:05 UTC | |
|
Re: A few very basic questions about Extending Perl
by juster (Friar) on Dec 26, 2010 at 17:58 UTC | |
by unlinker (Monk) on Dec 26, 2010 at 19:57 UTC | |
by unlinker (Monk) on Dec 29, 2010 at 08:58 UTC |