I'm working on a module that will allow you to directly support C and C++
structs in Perl. It is not an Inline Language. It will allow you to bind C
types directly into perl, something like this (although this isn't
complete):
----8<----
use Inline::Struct;
my $obj = new Foo;
$obj->a = 10;
print $obj->a . "\n";
my $o = bless { a => 12, b => "NEILW" }, "Foo";
print $_ . "\n" for (sort keys %$obj);
__END__
__Struct__
struct Foo {
int a;
char *b;
};
----8<----
This program would output:
10
a
b
Okay, that's kind of neat. But the useful part of this module will be that
Inline::Struct will be able to generate typemaps and header files for
later inclusion in Inline::C and Inline::CPP sections:
----8<----
use Inline::Struct;
use Inline C => 'DATA',
Struct => [qw(Person)];
my $n = bless ["neil", 10, 20], "Person";
my $j = bless { name => "jared",
data => 5,
some => 15}, "Person";
introduce($n, $j);
__END__
__Struct__
typedef struct {
char *name;
int some;
long data;
} Person;
__C__
void introduce(Person *first, Person *second) {
printf("%s says `Hi, %s!'\n", first->name, second->name);
printf("%s replies `Nice to meet you, %s.\n", second->name,
first->name);
}
----8<----
A (growing) summary of proposed features:
o binding to C structures from Perl
o each structure creates a corresponding Perl package
o individual elements of the struct can be directly modified in Perl
space, without having to go through accessor functions in C.
o automatic typemap and header file generation for later use in C(++)
sections.
o automatic memory handling (you bless a perl structure into a class, or
use the provided new() functions). From C, you can use something as
simple as this:
Person *f = new_Person("neil", 10, 20);
This will automatically malloc the new memory for you. If you return a
struct through the "C-Perl barrier", it will be automatically blessed
into the appropriate Perl type, and Perl will assume responsibility for
free()ing the memory associated with it. That means you should most
definitely not free it yourself.
o you can easily create mixed C/Perl classes, or C++ classes with
some member functions implemented in Perl. Because you have access to
the C internals of the structure, you can do something like this:
use Inline Struct;
my $o = new Mixed;
$o->some_function(1,2);
$o->dump;
package Struct;
use Inline C => 'DATA', Struct => [qw(Mixed)];
sub dump {
my $o = shift;
use Data::Dumper;
print Dumper $o;
}
__END__
__Struct__
struct Mixed { ... };
__C__
void some_function(Struct *o, int some, long args) { }
Later,
Neil