Perl OOP in pure C
- Makefile.PL
use 5.008009;
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => 'GPS',
VERSION_FROM => 'GPS.pm',
PREREQ_PM => {},
ABSTRACT_FROM => 'GPS.pm',
AUTHOR => 'Ziggi Stardust',
LIBS => [''],
DEFINE => '',
INC => '',
# OBJECT => '$(O_FILES)',
);
- GPS.pm
package GPS;
use strict;
use Carp;
use vars qw ($VERSION @ISA @EXPORT @EXPORT_OK $AUTOLOAD);
require DynaLoader;
use AutoLoader 'AUTOLOAD';
@ISA = qw(DynaLoader);
$VERSION = '0.01';
bootstrap GPS $VERSION;
BEGIN { }
1;
__END__
- GPS.xs
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
typedef struct data {
char *date;
char *serial;
} DATA;
typedef DATA* GPS;
MODULE = GPS PACKAGE = GPS
PROTOTYPES: DISABLE
GPS
new(class)
SV *class;
PREINIT:
DATA* data;
CODE:
if ((data = malloc(sizeof(DATA))) == NULL) {
croak("GPS new");
}
data->serial = "";
data->date = "";
RETVAL = data;
OUTPUT:
RETVAL
void*
set_serial(class, serial_SV)
GPS class;
SV* serial_SV;
CODE:
class->serial = SvPV_nolen(serial_SV);
char*
get_serial(class)
GPS class;
CODE:
RETVAL = class->serial;
OUTPUT:
RETVAL
void*
set_date(class, date_SV)
GPS class;
SV* date_SV;
CODE:
class->date = SvPV_nolen(date_SV);
char*
get_date(class)
GPS class;
CODE:
RETVAL = class->date;
OUTPUT:
RETVAL
SV *
get_data(class);
GPS class;
PREINIT:
HV *hash;
char *date_label = "date";
char *serial_label = "serial";
CODE:
hash = newHV();
hv_store(hash, date_label, strlen(date_label), newSVpv(class->date, strlen(class->date)), 0);
hv_store(hash, serial_label, strlen(serial_label), newSVpv(class->serial, strlen(class->serial)), 0);
RETVAL = newRV_noinc((SV*)hash);
OUTPUT:
RETVAL
- typemap
GPS T_PTROBJ
- gps.pl
#!/usr/local/bin/perl
use strict;
use Mojo::Util qw(dumper);
my $b = GPS->new;
$b->set_serial('0x123');
$b->set_date('1970-11-01');
print dumper $b->get_data;
# perl Makefile.PL
# make
# make install
# ./gps.pl
{
"date" => "",
"serial" => ""
}
{
"date" => "1970-11-01",
"serial" => "0x123"
}