Debian Codegraph @

lib/FFI/Platypus/Record.pm

raw
1 package FFI::Platypus::Record;
2
3 use strict;
4 use warnings;
5 use 5.008004;
6 use Carp qw( croak );
7 use FFI::Platypus;
8 use Exporter qw( import );
9 use constant 1.32 ();
10
11 our @EXPORT = qw( record_layout record_layout_1 );
12
13 # ABSTRACT: FFI support for structured records data
14 our $VERSION = '2.12'; # VERSION
15
16
17 sub record_layout_1
18 {
19 if(@_ % 2 == 0)
20 {
21 my $ffi = FFI::Platypus->new( api => 2);
22 unshift @_, $ffi;
23 goto &record_layout;
24 }
25 elsif(defined $_[0] && ref($_[0]) eq 'ARRAY')
26 {
27 my @args = @{ shift @_ };
28 unshift @args, api => 2;
29 unshift @_, \@args;
30 goto &record_layout;
31 }
32 elsif(defined $_[0] && eval { $_[0]->isa('FFI::Platypus') })
33 {
34 goto &record_layout;
35 }
36 else
37 {
38 croak "odd number of arguments, but first argument is not either an array reference or Platypus instance";
39 }
40 }
41
42
43 sub record_layout
44 {
45 my $ffi;
46
47 if(defined $_[0])
48 {
49 if(ref($_[0]) eq 'ARRAY')
50 {
51 my @args = @{ shift() };
52 $ffi = FFI::Platypus->new(@args);
53 }
54 elsif(eval { $_[0]->isa('FFI::Platypus') })
55 {
56 $ffi = shift;
57 }
58 }
59
60 $ffi ||= FFI::Platypus->new;
61
62 my $offset = 0;
63 my $record_align = 0;
64
65 croak "uneven number of arguments!" if scalar(@_) % 2;
66
67 my($caller, $filename, $line) = caller;
68
69 if($caller->can("_ffi_record_size")
70 || $caller->can("ffi_record_size"))
71 {
72 croak "record already defined for the class $caller";
73 }
74
75 my @destroy;
76 my @ffi_types;
77 my $has_string;
78
79 while(@_)
80 {
81 my $spec = shift;
82 my $name = shift;
83 my $type = $ffi->{tp}->parse( $spec, { member => 1 } );
84
85 croak "illegal name $name"
86 unless $name =~ /^[A-Za-z_][A-Za-z_0-9]*$/
87 || $name eq ':';
88 croak "accessor/method $name already exists"
89 if $caller->can($name);
90
91 my $size = $type->sizeof;
92 my $align = $type->alignof;
93 $record_align = $align if $align > $record_align;
94 my $meta = $type->meta;
95
96 $offset++ while $offset % $align;
97
98 {
99 my $count;
100 my $ffi_type;
101
102 if($meta->{type} eq 'record') # this means fixed string atm
103 {
104 $ffi_type = 'sint8';
105 $count = $size;
106 }
107 else
108 {
109 $ffi_type = $meta->{ffi_type};
110 $count = $meta->{element_count};
111 $count = 1 unless defined $count;
112
113 $has_string = 1 if $meta->{type} eq 'string';
114 }
115 push @ffi_types, $ffi_type for 1..$count;
116 }
117
118 if($name ne ':')
119 {
120
121 if($meta->{type} eq 'string'
122 && $meta->{access} eq 'rw')
123 {
124 push @destroy, eval '# line '. __LINE__ . ' "' . __FILE__ . qq("\n) .qq{
125 sub {
126 shift->$name(undef);
127 };
128 };
129 die $@ if $@;
130 }
131
132 my $full_name = join '::', $caller, $name;
133 my $error_str = _accessor
134 $full_name,
135 "$filename:$line",
136 $type,
137 $offset;
138 croak("$error_str ($spec $name)") if $error_str;
139 };
140
141 $offset += $size;
142 }
143
144 my $size = $offset;
145
146 no strict 'refs';
147 constant->import("${caller}::_ffi_record_size", $size);
148 constant->import("${caller}::_ffi_record_align", $record_align);
149 *{join '::', $caller, '_ffi_record_ro'} = \&_ffi_record_ro;
150 *{join '::', $caller, 'new'} = sub {
151 my $class = shift;
152 my $args = ref($_[0]) ? [%{$_[0]}] : \@_;
153 croak "uneven number of arguments to record constructor"
154 if @$args % 2;
155 my $record = "\0" x $class->_ffi_record_size;
156 my $self = bless \$record, $class;
157
158 while(@$args)
159 {
160 my $key = shift @$args;
161 my $value = shift @$args;
162 $self->$key($value);
163 }
164
165 $self;
166 };
167
168 {
169 require FFI::Platypus::Record::Meta;
170 my $ffi_meta = FFI::Platypus::Record::Meta->new(
171 \@ffi_types,
172 !$has_string,
173 );
174 *{join '::', $caller, '_ffi_meta'} = sub { $ffi_meta };
175 }
176
177 my $destroy_sub = sub {};
178
179 if(@destroy)
180 {
181 $destroy_sub = sub {
182 return if _ffi_record_ro($_[0]);
183 $_->($_[0]) for @destroy;
184 };
185 }
186 do {
187 no strict 'refs';
188 *{"${caller}::DESTROY"} = $destroy_sub;
189 };
190 ();
191 }
192
193 1;
194
195 __END__
196
197 =pod
198
199 =encoding UTF-8
200
201 =head1 NAME
202
203 FFI::Platypus::Record - FFI support for structured records data
204
205 =head1 VERSION
206
207 version 2.12
208
209 =head1 SYNOPSIS
210
211 C:
212
213 struct my_person {
214 int age;
215 const char title[3];
216 const char *name
217 };
218
219 void process_person(struct my_person *person)
220 {
221 /* ... */
222 }
223
224 Perl:
225
226 package MyPerson;
227
228 use FFI::Platypus::Record;
229
230 record_layout_1(
231 'int' => 'age',
232 'string(3)' => 'title',
233 'string rw' => 'name',
234 );
235
236 package main;
237
238 use FFI::Platypus 2.00;
239
240 my $ffi = FFI::Platypus->new( api => 2 );
241 $ffi->lib("myperson.so");
242 $ffi->type("record(MyPerson)" => 'MyPerson');
243
244 my $person = MyPerson->new(
245 age => 40,
246 title => "Mr.",
247 name => "John Smith",
248 );
249
250 $ffi->attach( process_person => [ 'MyPerson*' ] => 'void' );
251
252 process_person($person);
253
254 $person->age($person->age + 1); # another year older
255
256 process_person($person);
257
258 =head1 DESCRIPTION
259
260 [version 0.21]
261
262 This module provides a mechanism for building classes that can be used
263 to mange structured data records (known as C as "structs" and in some
264 languages as "records"). A structured record is a series of bytes that
265 have structure understood by the C or other foreign language library
266 that you are interfacing with. It is designed for use with FFI and
267 L<FFI::Platypus>, though it may have other applications.
268
269 Before you get to deep into using this class you should also consider
270 the L<FFI::C>, which provides some overlapping functionality. Briefly,
271 it comes down to this:
272
273 (The tl;dr is: use this class when you need to pass by value (since
274 L<FFI::C> does not support pass by value) and use L<FFI::C> in all
275 other circumstances).
276
277 =over 4
278
279 =item L<FFI::Platypus::Record>
280
281 Supports:
282
283 =over 4
284
285 =item C pointers to C<struct> types
286
287 =item Passing C C<struct>s by-value.
288
289 =back
290
291 Does not support:
292
293 =over 4
294
295 =item C C<union> types.
296
297 =item C arrays of C<struct> and C<union> types.
298
299 =back
300
301 =item L<FFI::C>
302
303 Supports:
304
305 =over 4
306
307 =item C C<struct> andC<union> types
308
309 =item C arrays of C<struct> and C<union> types.
310
311 =back
312
313 Does not support:
314
315 =over 4
316
317 =item Passing C C<struct>s by-value.
318
319 =back
320
321 String members are as of this writing a TODO for L<FFI::C>, but
322 should be coming soon!
323
324 =back
325
326 =head1 FUNCTIONS
327
328 =head2 record_layout_1
329
330 record_layout_1($ffi, $type => $name, ... );
331 record_layout_1(\@ffi_args, $type => $name, ... );
332 record_layout_1($type => $name, ... );
333
334 Define the layout of the record. You may optionally provide an instance
335 of L<FFI::Platypus> as the first argument in order to use its type
336 aliases. Alternatively you may provide constructor arguments that will
337 be passed to the internal platypus instance. Thus this is the same:
338
339 my $ffi = FFI::Platypus->new( lang => 'Rust', api => 2 );
340 record_layout_1( $ffi, ... );
341 # same as:
342 record_layout_1( [ lang => 'Rust' ], ... );
343
344 and this is the same:
345
346 my $ffi = FFI::Platypus->new( api => 2 );
347 record_layout_1( $ffi, ... );
348 # same as:
349 record_layout_1( ... );
350
351 Then you provide members as type/name pairs.
352
353 For each member you declare, C<record_layout_1> will create an accessor
354 which can be used to read and write its value. For example imagine a
355 class C<Foo>:
356
357 package Foo;
358
359 use FFI::Platypus::Record;
360
361 record_layout_1(
362 int => 'bar', # int bar;
363 'string(10)' => 'baz', # char baz[10];
364 );
365
366 You can get and set its fields with like named C<bar> and C<baz>
367 accessors:
368
369 my $foo = Foo->new;
370
371 $foo->bar(22);
372 my $value = $foo->bar;
373
374 $foo->baz("grimlock\0\0"); # should be 10 characters long
375 my $string_value = $foo->baz; # includes the trailing \0\0
376
377 You can also pass initial values in to the constructor, either passing
378 as a list of key value pairs or by passing a hash reference:
379
380 $foo = Foo->new(
381 bar => 22,
382 baz => "grimlock\0\0",
383 );
384
385 # same as:
386
387 $foo = Foo->new( {
388 bar => 22,
389 baz => "grimlock\0\0",
390 } );
391
392 If there are members of a record that you need to account for in terms
393 of size and alignment, but do not want to have an accessor for, you can
394 use C<:> as a place holder for its name:
395
396 record_layout_1(
397 'int' => ':',
398 'string(10)' => 'baz',
399 );
400
401 =head3 strings
402
403 So far I've shown fixed length strings. These are declared with the
404 word C<string> followed by the length of the string in parentheticals.
405 Fixed length strings are included inside the record itself and do not
406 need to be allocated or deallocated separately from the record.
407 Variable length strings must be allocated on the heap, and thus require
408 a sense of "ownership", that is whomever allocates variable length
409 strings should be responsible for also free'ing them. To handle this,
410 you can add a C<ro> or C<rw> trait to a string field. The default is
411 C<ro>, means that you can get, but not set its value:
412
413 package Foo;
414
415 record_layout_1(
416 'string ro' => 'bar', # same type as 'string' and 'string_ro'
417 );
418
419 package main;
420
421 my $foo = Foo->new;
422
423 my $string = $foo->bar; # GOOD
424 $foo->bar("starscream"); # BAD
425
426 If you specify a field is C<rw>, then you can set its value:
427
428 package Foo;
429
430 record_layout_1(
431 'string rw' => 'bar', # same type as 'string_rw'
432 );
433
434 package main;
435
436 my $foo = Foo->new;
437
438 my $string = $foo->bar; # GOOD
439 $foo->bar("starscream"); # GOOD
440
441 Any string value that is pointed to by the record will be free'd when it
442 falls out of scope, so you must be very careful that any C<string rw>
443 fields are not set or modified by C code. You should also take care not
444 to copy any record that has a C<rw> string in it because its values will
445 be free'd twice!
446
447 use Clone qw( clone );
448
449 my $foo2 = clone $foo; # BAD bar will be free'd twice
450
451 =head3 arrays
452
453 Arrays of integer, floating points and opaque pointers are supported.
454
455 package Foo;
456
457 record_layout_1(
458 'int[10]' => 'bar',
459 );
460
461 my $foo = Foo->new;
462
463 $foo->bar([1,2,3,4,5,6,7,8,9,10]); # sets the values for the array
464 my $list = $foo->bar; # returns a list reference
465
466 $foo->bar(5, -6); # sets the 5th element in the array to -6
467 my $item = $foo->bar(5); gets the 5th element in the array
468
469 =head2 record_layout
470
471 record_layout($ffi, $type => $name, ... );
472 record_layout(\@ffi_args, $type => $name, ... );
473 record_layout($type => $name, ... );
474
475 This function works like C<record_layout> except that
476 C<api =E<gt> 0> is used instead of C<api =E<gt> 1>.
477 All new code should use C<record_layout_1> instead.
478
479 =head1 CAVEATS
480
481 These useful features (and probably more) are missing, and unlikely to be added.
482
483 =over 4
484
485 =item Unions
486
487 =item Nested records
488
489 =back
490
491 If you need these features, consider using L<FFI::C> instead.
492
493 =head1 SEE ALSO
494
495 =over 4
496
497 =item L<FFI::Platypus>
498
499 The main platypus documentation.
500
501 =item L<FFI::C>
502
503 Another interface for constructing structured data. It includes support for
504 C<union> and array types (which this module does not), but lacks support for
505 passing records by-value.
506
507 =item L<FFI::Platypus::Record::TieArray>
508
509 Tied array interface for record array members.
510
511 =item L<Convert::Binary::C>
512
513 Another method for constructing and dissecting structured data records.
514
515 =item L<pack and unpack|perlpacktut>
516
517 Built-in Perl functions for constructing and dissecting structured data
518 records.
519
520 =back
521
522 =head1 AUTHOR
523
524 Author: Graham Ollis E<lt>[email protected]<gt>
525
526 Contributors:
527
528 Bakkiaraj Murugesan (bakkiaraj)
529
530 Dylan Cali (calid)
531
532 pipcet
533
534 Zaki Mughal (zmughal)
535
536 Fitz Elliott (felliott)
537
538 Vickenty Fesunov (vyf)
539
540 Gregor Herrmann (gregoa)
541
542 Shlomi Fish (shlomif)
543
544 Damyan Ivanov
545
546 Ilya Pavlov (Ilya33)
547
548 Petr Písař (ppisar)
549
550 Mohammad S Anwar (MANWAR)
551
552 Håkon Hægland (hakonhagland, HAKONH)
553
554 Meredith (merrilymeredith, MHOWARD)
555
556 Diab Jerius (DJERIUS)
557
558 Eric Brine (IKEGAMI)
559
560 szTheory
561
562 José Joaquín Atria (JJATRIA)
563
564 Pete Houston (openstrike, HOUSTON)
565
566 Lukas Mai (MAUKE)
567
568 =head1 COPYRIGHT AND LICENSE
569
570 This software is copyright (c) 2015-2022 by Graham Ollis.
571
572 This is free software; you can redistribute it and/or modify it under
573 the same terms as the Perl 5 programming language system itself.
574
575 =cut