File: Def.pm

package info (click to toggle)
libffi-c-perl 0.15-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 484 kB
  • sloc: perl: 1,517; ansic: 57; sh: 19; makefile: 2
file content (529 lines) | stat: -rw-r--r-- 11,409 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
package FFI::C::Def;

use strict;
use warnings;
use 5.008001;
use FFI::C::FFI qw( malloc memset );
use FFI::C::Util;
use Ref::Util qw( is_blessed_ref is_ref is_plain_hashref is_plain_arrayref );
use Sub::Install ();
use Sub::Util ();

our @CARP_NOT = qw( FFI::C );

# ABSTRACT: Data definition for FFI
our $VERSION = '0.15'; # VERSION


sub new
{
  my $class = shift;

  Carp::croak("Attempt to call new on a def object (did you mean ->create?)") if is_blessed_ref $class;

  my $ffi = is_blessed_ref($_[0]) && $_[0]->isa('FFI::Platypus') ? shift : FFI::Platypus->new( api => 1 );
  my %args = @_;

  Carp::croak("Only works with FFI::Platypus api level 1 or better") unless $ffi->api >= 1;
  Carp::croak("FFI::C::Def is an abstract class") if $class eq 'FFI::C::Def';

  my $self = bless {
    ffi      => $ffi,
    name     => delete $args{name},
    class    => delete $args{class},
    nullable => delete $args{nullable},
    members  => {},
    align    => 0,
    size     => 0,
    args     => \%args,
  }, $class;

  if($self->name)
  {
    my $cdef = ref($self);
    $cdef =~ s/Def$//;
    $ffi->load_custom_type('::CDef' => $self->name,
      name     => $self->name,
      class    => $self->class,
      nullable => $self->nullable,
      def      => $self,
      cdef    => $cdef,
    );
    $ffi->def('FFI::C::Def', $self->name, $self);
  }

  $self;
}

sub _generate_class
{
  my($self, @accessors) = @_;

  # first run through all the members, and make sure that we
  # can generate a class based on the def.  That means that:
  #  1. there is no constructor or destructor defined yet.
  #  2. none of the member accessors already exist
  #  3. Any nested cdefs have Perl classes, this will be done
  #     in the subclass

  foreach my $method (qw( new DESTROY ))
  {
    my $accessor = join '::', $self->class, $method;
    Carp::croak("$accessor already defined") if $self->class->can($method);
  }

  foreach my $name (@accessors)
  {
    next if $name =~ /^:/;
    my $accessor = $self->class . '::' . $name;
    Carp::croak("$accessor already exists")
      if $self->class->can($name);
  }

  require FFI::Platypus::Memory;

  if($self->isa('FFI::C::ArrayDef'))
  {

    my $size = $self->size;
    my $count = $self->{members}->{count};
    my $member_size = $self->{members}->{member}->size;

    my $code = sub {
      my $class = shift;
      my($ptr, $owner);

      my $size  = $size;
      my $count = $count;
      if(@_ == 1)
      {
        if(!is_ref $_[0])
        {
          $count = shift;
        }
        elsif(is_plain_arrayref $_[0])
        {
          $count = scalar @{$_[0]};
        }
        if($count)
        {
          $size = $member_size * $count;
        }
      }

      if(@_ == 2 && ! is_ref $_[0])
      {
        ($ptr, $owner) = @_;
      }
      else
      {
        Carp::croak("Cannot create array without knowing the number of elements")
          unless $size;
        $ptr = FFI::Platypus::Memory::malloc($size);
        FFI::Platypus::Memory::memset($ptr, 0, $size);
      }
      my $self = bless {
        ptr   => $ptr,
        owner => $owner,
        count => $count,
      }, $class;
      FFI::C::Util::perl_to_c($self, $_[0]) if @_ == 1 && is_ref $_[0];
      $self;
    };

    Sub::Util::set_subname(join('::', $self->class, 'new'), $code);
    Sub::Install::install_sub({
      code => $code,
      into => $self->class,
      as   => 'new',
    });
  }
  else
  {
    my $size = $self->size;
    $size = 1 unless $size > 0;

    my $code =       sub {
      my $class = shift;
      my($ptr, $owner);
      if(@_ == 2 && ! is_ref $_[0])
      {
        ($ptr, $owner) = @_;
      }
      else
      {
        $ptr = FFI::Platypus::Memory::malloc($size);
        FFI::Platypus::Memory::memset($ptr, 0, $size);
      }
      my $self = bless {
        ptr => $ptr,
        owner => $owner,
      }, $class;
      FFI::C::Util::perl_to_c($self, $_[0]) if @_ == 1 && is_ref $_[0];
      $self;
    };

    Sub::Util::set_subname(join('::', $self->class, 'new'), $code);
    Sub::Install::install_sub({
      code => $code,
      into => $self->class,
      as   => 'new',
    });
  }

  Sub::Install::install_sub({
    code => \&_common_destroy,
    into => $self->class,
    as   => 'DESTROY',
  });
}

sub _common_destroy
{
  my($self) = @_;
  if($self->{ptr} && !$self->{owner})
  {
    FFI::Platypus::Memory::free(delete $self->{ptr});
  }
}


sub name     { shift->{name} }
sub class    { shift->{class} }
sub ffi      { shift->{ffi} }
sub size     { shift->{size} }
sub align    { shift->{align} }
sub nullable { shift->{nullable} }


sub create
{
  my $self = shift;

  return $self->class->new(@_) if $self->class;

  my $ptr;
  my $owner;

  if(@_ == 2 && ! is_ref $_[0])
  {
    ($ptr, $owner) = @_;
  }
  else
  {
    # TODO: we use 1 byte for size 0
    # this is needed if malloc(0) returns undef.
    # we could special case for platforms where malloc(0)
    # returns a constant pointer that can be free()'d
    $ptr = malloc($self->size ? $self->size : 1);
    memset($ptr, 0, $self->size);
  }

  my $class = ref($self);
  $class =~ s/Def$//;

  my $inst = bless {
    ptr   => $ptr,
    def   => $self,
    owner => $owner,
  }, $class;

  FFI::C::Util::perl_to_c($inst, $_[0]) if @_ == 1 && is_plain_hashref $_[0];

  $inst;
}

package FFI::Platypus::Type::CDef;

use Ref::Util qw( is_blessed_ref );

push @FFI::Platypus::CARP_NOT, __PACKAGE__;

sub ffi_custom_type_api_1
{
  my(undef, undef, %args) = @_;

  my $perl_to_native;
  my $native_to_perl;

  my $name     = $args{name};
  my $class    = $args{class};
  my $def      = $args{def}  || Carp::croak("no def defined");
  my $cdef     = $args{cdef} || Carp::croak("no cdef defined");
  my $nullable = $args{nullable};

  if($class)
  {
    $perl_to_native = sub {
      return undef if !defined $_[0] && $nullable;
      Carp::croak("argument is not a $class")
        unless is_blessed_ref $_[0]
        && $_[0]->isa($class);
      my $ptr = $_[0]->{ptr};
      Carp::croak("pointer for $name went away")
        unless defined $ptr;
      $ptr;
    };
    $native_to_perl = sub {
      defined $_[0]
        ? bless { ptr => $_[0], owner => 1 }, $class
        : undef;
    };
  }

  elsif($name)
  {
    $perl_to_native = sub {
      return undef if !defined $_[0] && $nullable;
      Carp::croak("argument is not a $name")
        unless is_blessed_ref $_[0]
        && ref($_[0]) eq $cdef
        && $_[0]->{def}->{name} eq $name;
      my $ptr = $_[0]->{ptr};
      Carp::croak("pointer for $name went away")
        unless defined $ptr;
      $ptr;
    };
    $native_to_perl = sub {
      defined $_[0]
        ? bless { ptr => $_[0], def => $def, owner => 1 }, $cdef
        : undef;
    };
  }

  return {
    native_type    => 'opaque',
    perl_to_native => $perl_to_native,
    native_to_perl => $native_to_perl,
  }
}

package FFI::C::EnumDef;

sub new
{
  my($class, %self) = @_;
  bless \%self, $class;
}

sub str_lookup { shift->{str_lookup} }
sub int_lookup { shift->{int_lookup} }
sub type { shift->{type} }
sub rev { shift->{rev} }

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

FFI::C::Def - Data definition for FFI

=head1 VERSION

version 0.15

=head1 SYNOPSIS

In your C code:

 #include <stdint.h>
 #include <stdio.h>
 
 typedef struct {
   uint8_t red;
   uint8_t green;
   uint8_t blue;
 } color_t;
 
 void
 print_color(color_t *c)
 {
   printf("[%02x %02x %02x]\n",
     c->red,
     c->green,
     c->blue
   );
 }

In your Perl code:

 use FFI::Platypus 1.00;
 use FFI::C::StructDef;
 
 my $ffi = FFI::Platypus->new( api => 1 );
 # See FFI::Platypus::Bundle for how bundle works.
 $ffi->bundle;
 
 my $def = FFI::C::StructDef->new(
   $ffi,
   name  => 'color_t',
   class => 'Color',
   members => [
     red   => 'uint8',
     green => 'uint8',
     blue  => 'uint8',
   ],
 );
 
 my $red = Color->new({ red => 255 });
 
 my $green = Color->new({ green => 255 });
 
 $ffi->attach( print_color => ['color_t'] );
 
 print_color($red);   # [ff 00 00]
 print_color($green); # [00 ff 00]
 
 # that red is a tad bright!
 $red->red( 200 );
 
 print_color($red);   # [c8 00 00]

=head1 DESCRIPTION

This class is the base class for all def classes in the L<FFI::C> collection.
The def classes are for defining C C<struct>, C<union> and array types that
can be used from Perl and passed to C via L<FFI::Platypus>.

You don't create an instance of this class directly, rather one of the subclasses:
L<FFI::C::StructDef>, L<FFI::C::UnionDef>, L<FFI::C::ArrayDef>.

=head1 CONSTRUCTOR

=head2 new

 my $def = FFI::C::StructDef->new(%opts);
 my $def = FFI::C::StructDef->new($ffi, %opts);
 my $def = FFI::C::UnionDef->new(%opts);
 my $def = FFI::C::UnionDef->new($ffi, %opts);
 my $def = FFI::C::ArrayDef->new(%opts);
 my $def = FFI::C::ArrayDef->new($ffi, %opts);

The constructor for this class shouldn't be invoked directly.  If you try
and exception will be thrown.

For subclasses, the first argument should be the L<FFI::Platypus> instance
that you want to use with the def.  If you do not provide it, then one
will be created internally for you.  All def classes accept these standard options:

=over 4

=item name

The L<FFI::Platypus> alias for this def.  This name can be used
in function signatures when creating or attaching functions in L<FFI::Platypus>.

=item class

The Perl class for this def.  The Perl class can be used to create an instance
of this def instead of invoking the C<create> method below.

=item members

This is an array reference, which specifies the member fields for the
def.  How exactly it works depends on the subclass, so see the documentation
for the specific def class that you are using.

=item nullable

If true, then the type can be C<undef> when passed into C.  C<undef> will be translated
to C<NULL>.

=back

=head1 METHODS

=head2 ffi

 my $ffi = $def->ffi;

Returns the L<FFI::Platypus> instance used by this def.

=head2 name

 my $name = $def->name;

Return the L<FFI::Platypus> alias for this def.  This name can be used
in function signatures when creating or attaching functions in L<FFI::Platypus>.

=head2 class

 my $class = $def->class;

Returns the Perl class for this def, if one was specified.  The Perl class
can be used to create an instance of this def instead of invoking the
C<create> method below.

=head2 size

 my $size = $def->size;

Returns the size of the def in bytes.

=head2 align

 my $align = $def->align;

Returns the alignment in bytes of the def.

=head2 nullable

 my $bool = $def->nullable;

Returns true if C<undef> is allowed to be passed in to C functions.  C<undef> will
be translated to C<NULL>.

=head2 create

 my $instance = $def->create;
 my $instance = $def->class->new;  # if class was specified

Creates an instance of the def.

=head1 SEE ALSO

=over 4

=item L<FFI::C>

=item L<FFI::C::Array>

=item L<FFI::C::ArrayDef>

=item L<FFI::C::Def>

=item L<FFI::C::File>

=item L<FFI::C::PosixFile>

=item L<FFI::C::Struct>

=item L<FFI::C::StructDef>

=item L<FFI::C::Union>

=item L<FFI::C::UnionDef>

=item L<FFI::C::Util>

=item L<FFI::Platypus::Record>

=back

=head1 AUTHOR

Graham Ollis <plicease@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2020-2022 by Graham Ollis.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut