Debian Codegraph @

lib/FFI/Platypus/Type.pm

raw
1 package FFI::Platypus::Type;
2
3 use strict;
4 use warnings;
5 use 5.008004;
6 use Carp qw( croak );
7 require FFI::Platypus;
8
9 # ABSTRACT: Defining types for FFI::Platypus
10 our $VERSION = '2.12'; # VERSION
11
12 # The TypeParser and Type classes are used internally ONLY and
13 # are not to be exposed to the user. External users should
14 # not under any circumstances rely on the implementation of
15 # these classes.
16
17 sub alignof
18 {
19 my($self) = @_;
20 my $meta = $self->meta;
21
22 # TODO: it is possible, though complicated
23 # to compute the alignment of a struct
24 # type record.
25 croak "cannot determine alignment of record"
26 if $meta->{type} eq 'record'
27 && $meta->{ref} == 1;
28
29 my $ffi_type;
30 if($meta->{type} eq 'pointer')
31 {
32 $ffi_type = 'pointer';
33 }
34 elsif($meta->{type} eq 'record')
35 {
36 $ffi_type = 'uint8';
37 }
38 else
39 {
40 $ffi_type = $meta->{ffi_type};
41 }
42
43 require FFI::Platypus::ShareConfig;
44 FFI::Platypus::ShareConfig->get('align')->{$ffi_type};
45 }
46
47 1;
48
49 __END__
50
51 =pod
52
53 =encoding UTF-8
54
55 =head1 NAME
56
57 FFI::Platypus::Type - Defining types for FFI::Platypus
58
59 =head1 VERSION
60
61 version 2.12
62
63 =head1 SYNOPSIS
64
65 OO Interface:
66
67 use FFI::Platypus 2.00;
68 my $ffi = FFI::Platypus->new( api => 2 );
69 $ffi->type('int' => 'my_int');
70
71 =head1 DESCRIPTION
72
73 B<Note>: This document assumes that you are using C<api =E<gt> 2>,
74 which you should be using for all new code.
75
76 This document describes how to define types using L<FFI::Platypus>.
77 Types may be "defined" ahead of time, or simply used when defining or
78 attaching functions.
79
80 # Example of defining types
81 use FFI::Platypus 2.00;
82 my $ffi = FFI::Platypus->new( api => 2 );
83 $ffi->type('int');
84 $ffi->type('string');
85
86 # Example of simply using types in function declaration or attachment
87 my $f = $ffi->function(puts => ['string'] => 'int');
88 $ffi->attach(puts => ['string'] => 'int');
89
90 Unless you are using aliases the L<FFI::Platypus#type> method is not
91 necessary, but they will throw an exception if the type is incorrectly
92 specified or not supported, which may be helpful for determining if
93 the types are available or not.
94
95 Note: This document sometimes uses the term "C Function" as short hand
96 for function implemented in a compiled language. Unless the term is
97 referring literally to a C function example code, you can assume that
98 it should also work with another compiled language.
99
100 =head2 meta information about types
101
102 You can get the size of a type using the L<FFI::Platypus#sizeof> method.
103
104 my $intsize = $ffi->sizeof('int'); # usually 4
105 my $intarraysize = $ffi->sizeof('int[64]'); # usually 256
106
107 =head2 converting types
108
109 Sometimes it is necessary to convert types. In particular various
110 pointer types often need to be converted for consumption in Perl. For
111 this purpose the L<FFI::Platypus#cast> method is provided. It needs to
112 be used with care though, because not all type combinations are
113 supported. Here are some useful ones:
114
115 my $address = $ffi->cast('string' => 'opaque', $string);
116
117 This converts a Perl string to a pointer address that can be used
118 by functions that take an C<opaque> type. Be carefully though that
119 the Perl string is not resized or free'd while in use from C code.
120
121 my $string = $ffi->cast('opaque' => 'string', $pointer);
122
123 This does the opposite, converting a null terminated string (the
124 type of strings used by C) into a Perl string. In this case the
125 string is copied, so the other language is free to deallocate or
126 otherwise manipulate the string after the conversion without adversely
127 affecting the Perl.
128
129 =head2 aliases
130
131 Some times using alternate names is useful for documenting the purpose
132 of an argument or return type. For this "aliases" can be helpful. The
133 second argument to the L<FFI::Platypus#type> method can be used to
134 define a type alias that can later be used by function declaration
135 and attachment.
136
137 use FFI::Platypus 2.00;
138 my $ffi = FFI::Platypus->new( api => 2 );
139 $ffi->type('int' => 'myint');
140 $ffi->type('string' => 'mystring');
141 my $f = $ffi->function( puts => ['mystring'] => 'myint' );
142 $ffi->attach( puts => ['mystring'] => 'myint' );
143
144 Aliases are contained without the L<FFI::Platypus> object, so feel free
145 to define your own crazy types without stepping on the toes of other
146 CPAN developers using Platypus.
147
148 One useful application of an alias is when you know types are different
149 on two different platforms:
150
151 if($^O eq 'MSWin32')
152 {
153 $type->type('sint16' => 'foo_t');
154 } elsif($^O eq 'linux')
155 {
156 $type->type('sint32' => 'foo_t');
157 }
158
159 # function foo takes 16 bit signed integer on Windows
160 # and a 32 bit signed integer on Linux.
161 $ffi->attach( foo => [ 'foo_t' ] => 'void' );
162
163 =for stopwords tm
164
165 =head1 TYPE CATEGORIES
166
167 =head2 Native types
168
169 So called native types are the types that the CPU understands that can
170 be passed on the argument stack or returned by a function. It does not
171 include more complicated types like arrays or structs, which can be
172 passed via pointers (see the opaque type below). Generally native types
173 include void, integers, floats and pointers.
174
175 =head3 the void type
176
177 This can be used as a return value to indicate a function does not
178 return a value (or if you want the return value to be ignored).
179
180 $ffi->type( foo => [] => 'void' );
181
182 Newer versions of Platypus also allow you to omit the return type and
183 C<void> is assumed.
184
185 $ffi->type( foo => [] );
186
187 It doesn't really make sense to use C<void> in any other context. However,
188 because of historical reasons involving older versions of Perl.
189
190 It doesn't really make sense for C<void> to be passed in as an argument.
191 However, because C functions that take no arguments frequently are specified
192 as taking C<void> as this was required by older C compilers, as a special
193 case you can specify a function's arguments as taking a single C<void> to
194 mean it takes no arguments.
195
196 # C: void foo(void);
197 $ffi->type( foo => ['void'] );
198 # same (but probably better)
199 $ffi->type( foo => [] );
200
201 =head3 integer types
202
203 The following native integer types are always available (parentheticals
204 indicates the usual corresponding C type):
205
206 =over 4
207
208 =item sint8
209
210 Signed 8 bit byte (C<signed char>, C<int8_t>).
211
212 =item uint8
213
214 Unsigned 8 bit byte (C<unsigned char>, C<uint8_t>).
215
216 =item sint16
217
218 Signed 16 bit integer (C<short>, C<int16_t>)
219
220 =item uint16
221
222 Unsigned 16 bit integer (C<unsigned short>, C<uint16_t>)
223
224 =item sint32
225
226 Signed 32 bit integer (C<int>, C<int32_t>)
227
228 =item uint32
229
230 Unsigned 32 bit integer (C<unsigned int>, C<uint32_t>)
231
232 =item sint64
233
234 Signed 64 bit integer (C<long long>, C<int64_t>)
235
236 =item uint64
237
238 Unsigned 64 bit integer (C<unsigned long long>,
239 C<uint64_t>)
240
241 =back
242
243 You may also use C<uchar>, C<ushort>, C<uint> and C<ulong> as short
244 names for C<unsigned char>, C<unsigned short>, C<unsigned int> and
245 C<unsigned long>.
246
247 These integer types are also available, but there actual size and sign
248 may depend on the platform.
249
250 =over 4
251
252 =item char
253
254 Somewhat confusingly, C<char> is an integer type! This is really an
255 alias for either C<sint8_t> or C<uint8_t> depending on your platform.
256 If you want to pass a character (not integer) in to a C function that
257 takes a character you want to use the perl L<ord|perlfunc/ord> function.
258 Here is an example that uses the standard libc C<isalpha>, C<isdigit>
259 type functions:
260
261 use FFI::Platypus 2.00;
262
263 my $ffi = FFI::Platypus->new( api => 2 );
264 $ffi->lib(undef);
265 $ffi->type('int' => 'character');
266
267 my @list = qw(
268 alnum alpha ascii blank cntrl digit lower print punct
269 space upper xdigit
270 );
271
272 $ffi->attach("is$_" => ['character'] => 'int') for @list;
273
274 my $char = shift(@ARGV) || 'a';
275
276 no strict 'refs';
277 printf "'%s' is %s %s\n", $char, $_, &{'is'.$_}(ord $char) for @list;
278
279 =item size_t
280
281 This is usually an C<unsigned long>, but it is up to the compiler to
282 decide. The C<malloc> function is defined in terms of C<size_t>:
283
284 $ffi->attach( malloc => ['size_t'] => 'opaque';
285
286 (Note that you can get C<malloc> from L<FFI::Platypus::Memory>).
287
288 =item long, unsigned long
289
290 On 64 bit systems, this is usually a 64 bit integer. On 32 bit systems
291 this is frequently a 32 bit integer (and C<long long> or
292 C<unsigned long long> are for 64 bit).
293
294 =back
295
296 There are a number of other types that may or may not be available if
297 they are detected when L<FFI::Platypus> is installed. This includes
298 things like C<wchar_t>, C<off_t>, C<wint_t>. You can use this script to
299 list all the integer types that L<FFI::Platypus> knows about, plus how
300 they are implemented.
301
302 use FFI::Platypus 2.00;
303
304 my $ffi = FFI::Platypus->new( api => 2 );
305
306 foreach my $type_name (sort $ffi->types)
307 {
308 my $meta = $ffi->type_meta($type_name);
309 next unless defined $meta->{element_type} && $meta->{element_type} eq 'int';
310 printf "%20s %s\n", $type_name, $meta->{ffi_type};
311 }
312
313 If you need a common system type that is not provided, please open a
314 ticket in the Platypus project's GitHub issue tracker. Be sure to
315 include the usual header file the type can be found in.
316
317 =head3 Enum types
318
319 C provides enumerated types, which are typically implemented as integer
320 types.
321
322 enum {
323 BAR = 1,
324 BAZ = 2
325 } foo_t;
326
327 void f(enum foo_t foo);
328
329 Platypus provides C<enum> and C<senum> types for the integer types used
330 to represent enum and signed enum types respectively.
331
332 use constant BAR => 1;
333 use constant BAZ => 2;
334 $ffi->attach( f => [ 'enum' ] => 'void' );
335 f(BAR);
336 f(BAZ);
337
338 When do you use C<senum>? Anytime the enum has negative values:
339
340 enum {
341 BAR = -1;
342 BAZ = 2;
343 } foo_t;
344
345 void f(enum foo_t foo);
346
347 Perl:
348
349 use constant BAR => -1;
350 use constant BAZ => 2;
351 $ffi->attach( f => [ 'senum' ] => 'void' );
352 f(BAR);
353 f(BAZ);
354
355 Dealing with enumerated values with FFI can be tricky because these are
356 usually defined in C header files and cannot be found in dynamic libraries.
357 For trivial usage you can do as illustrated above, simply define your own
358 Perl constants. For more complicated usage, or where the values might vary
359 from platform to platform you may want to consider the new Platypus bundle
360 interface to define Perl constants (essentially the same as an enumerated
361 value) from C space. This is more reliable, but does require a compiler
362 at install time. See L<FFI::Platypus::Constant> for details.
363
364 The main FAQ (L<FFI::Platypus/FAQ>) also has a discussion on dealing
365 with constants and enumerated types.
366
367 There is also a type plugin (L<FFI::Platypus::Type::Enum>) that can be helpful
368 in writing interfaces that use enums.
369
370 =head3 Boolean types
371
372 At install time Platypus attempts to detect the correct type for C<bool>
373 for your platform, and you can use that. C<bool> is really an integer
374 type, but the type used varies from platform to platform.
375
376 C header:
377
378 #include <stdbool.h>
379 bool foo();
380
381 Platypus
382
383 $ffi->attach( foo => [] => 'bool' );
384
385 If you get an exception when trying to use this type it means you either
386 have a very old version of Platypus, or for some reason it was unable to
387 detect the correct type at install time. Please open a ticket if that is
388 the case.
389
390 =head3 floating point types
391
392 The following native floating point types are always available
393 (parentheticals indicates the usual corresponding C type):
394
395 =over 4
396
397 =item float
398
399 Single precision floating point (I<float>)
400
401 =item double
402
403 Double precision floating point (I<double>)
404
405 =item longdouble
406
407 Floating point that may be larger than C<double> (I<longdouble>). This
408 type is only available if supported by the C compiler used to build
409 L<FFI::Platypus>. There may be a performance penalty for using this
410 type, even if your Perl uses long doubles internally for its number
411 value (NV) type, because of the way L<FFI::Platypus> interacts with
412 C<libffi>.
413
414 As an argument type either regular number values (NV) or instances of
415 L<Math::LongDouble> are accepted. When used as a return type,
416 L<Math::LongDouble> will be used, if you have that module installed.
417 Otherwise the return type will be downgraded to whatever your Perl's
418 number value (NV) is.
419
420 =item complex_float
421
422 Complex single precision floating point (I<float complex>)
423
424 =item complex_double
425
426 Complex double precision floating point (I<double complex>)
427
428 C<complex_float> and C<complex_double> are only available if supported
429 by your C compiler and by libffi. Complex numbers are only supported in
430 very recent versions of libffi, and as of this writing the latest
431 production version doesn't work on x86_64. It does seem to work with
432 the latest production version of libffi on 32 bit Intel (x86), and with
433 the latest libffi version in git on x86_64.
434
435 =back
436
437 =head3 opaque pointers
438
439 Opaque pointers are simply a pointer to a region of memory that you do
440 not manage, and do not know or care about its structure. It is like
441 a C<void *> in C. These types are represented in Perl space as integers
442 and get converted to and from pointers by L<FFI::Platypus>. You may use
443 C<pointer> as an alias for C<opaque>, although this is discouraged.
444 (The Platypus documentation uses the convention of using "pointer"
445 to refer to pointers to known types (see below) and "opaque" as short
446 hand for opaque pointer).
447
448 As an example, libarchive defines C<struct archive> type in its header
449 files, but does not define its content. Internally it is defined as a
450 C<struct> type, but the caller does not see this. It is therefore
451 opaque to its caller. There are C<archive_read_new> and
452 C<archive_write_new> functions to create a new instance of this opaque
453 object and C<archive_read_free> and C<archive_write_free> to destroy
454 this objects when you are done.
455
456 C header:
457
458 struct archive;
459 struct archive *archive_read_new(void);
460 struct archive *archive_write_new(void);
461 int archive_free(struct archive *);
462 int archive_write_free(struct archive *);
463
464 Perl code:
465
466 $lib->find_lib( lib => 'archive' );
467 $ffi->attach(archive_read_new => [] => 'opaque');
468 $ffi->attach(archive_write_new => [] => 'opaque');
469 $ffi->attach(archive_read_free => ['opaque'] => 'int');
470 $ffi->attach(archive_write_free => ['opaque'] => 'int');
471
472 It is often useful to alias an C<opaque> type like this so that you know
473 what the object represents:
474
475 $lib->find_lib( lib => 'archive' );
476 $ffi->type('opaque' => 'archive');
477 $ffi->attach(archive_read_new => [] => 'archive');
478 $ffi->attach(archive_read_free => ['archive'] => 'int');
479 ...
480
481 As a special case, when you pass C<undef> into a function that takes an
482 opaque type it will be translated into C<NULL> for C. When a C function
483 returns a NULL pointer, it will be translated back to C<undef>.
484
485 For functions that take a pointer to a void pointer (that is a C<void **>),
486 you can use a pointer to an opaque type. Consider the C code:
487
488 struct archive_entry;
489 int archive_read_next_header(struct archive *, struvct archive_entry **);
490
491 Once again the internals of C<archive_entry> are not provided. Perl code:
492
493 $ffi->type('opaque' => 'archive_entry');
494 $ffi->attach(archive_read_next_header => [ 'archive', 'archive_entry*' ] => 'int');
495
496 Now we can call this function
497
498 my $archive = archive_read_new();
499 ... # additional prep for $active is required
500 while(1) {
501 my $entry;
502 archive_read_next_header($archive, \$entry);
503 last unless defined $entry;
504 # can now use $entry for other archive_entry_ methods.
505 }
506
507 The way C<archive_read_next_header> works, it will return a pointer to the next
508 C<archive_entry> object until it gets to the end, when it will return a pointer
509 to C<NULL> which will be represented in Perl by a C<undef>.
510
511 There are a number of useful utility functions for dealing with opaque
512 types in the L<FFI::Platypus::Memory> module.
513
514 =head2 Objects
515
516 Object types are thin wrappers around two native types: integer and
517 C<opaque> types. They are just blessed references around either of
518 those two types so that methods can be defined on them, but when they
519 get passed to a Platypus xsub they are converted into the native
520 integer or C<opaque> types. This type is most useful when a API
521 provides an OO style interface with an integer or C<opaque> value
522 acting as an instance of a class. There are two detailed examples
523 in the main Platypus documentation using libarchive and unix open:
524
525 =over 4
526
527 =item L<FFI::Platypus/libarchive>
528
529 =item L<FFI::Platypus/"unix open">
530
531 =back
532
533 =head2 Strings
534
535 # used when you need a char * or const char *
536 $ffi->attach( puts => [ 'string' ] => 'int' );
537
538 The C<string> type is a series of bytes that usually represent a
539 series of characters. They will be NULL terminated for C and passed
540 in as a pointer. This will typically work for APIs that take ASCII
541 or UTF-8 strings which are common in Unix environments.
542
543 (Note if you need to handle the native "wide" string for example
544 if you need to talk UTF-16 on Windows see L<FFI::Platypus::Type::WideString>).
545
546 (Note if you need to pass in a fixed length string by value (not as
547 a pointer) then you can do so using L<FFI::Platypus::Record>).
548
549 (Note that languages like L<Go|FFI::Platypus::Lang::Go> and L<Rust|FFI::Platypus::Lang::Rust> do not use NULL terminated strings
550 and need their own string types; see the appropriate language plugins for details)
551
552 # can also be used when you need a void * or const void *
553 $ffi->attach( write => ['int', 'string', 'size_t' ] => 'ssizet' );
554
555 The C<string> type can also be used to pass in the start of a buffer
556 of arbitrary bytes stored in a Perl scalar. Because a C<string> is
557 passed just as a pointer you will typically need to also pass the
558 length of the buffer as a separate argument. This is necessary because
559 buffers could potentially have a NULL in them.
560
561 The pointer passed into C (or other language) is to the content of the
562 actual scalar, which means it can modify the content of a scalar.
563
564 B<NOTE>: When used as a return type, the string is I<copied> into a
565 new scalar rather than using the original address. This is due to
566 the ownership model of scalars in Perl, but it is also most of the
567 time what you want.
568
569 This can be problematic when a function returns a string that the callee
570 is expected to free. Consider the functions:
571
572 char *
573 get_string()
574 {
575 char *buffer;
576 buffer = malloc(20);
577 strcpy(buffer, "Perl");
578 }
579
580 void
581 free_string(char *buffer)
582 {
583 free(buffer);
584 }
585
586 This API returns a string that you are expected to free when you are
587 done with it. (At least they have provided an API for freeing the
588 string instead of expecting you to call libc free)! A simple binding
589 to get the string would be:
590
591 $ffi->attach( get_string => [] => 'string' ); # memory leak
592 my $str = get_string();
593
594 Which will work to a point, but the memory allocated by get_string
595 will leak. Instead you need to get the opaque pointer, cast it to
596 a string and then free it.
597
598 $ffi->attach( get_string => [] => 'opaque' );
599 $ffi->attach( free_string => ['opaque'] => 'void' );
600 my $ptr = get_string();
601 my $str = $ffi->cast( 'opaque' => 'string', $ptr ); # copies the string
602 free_string($ptr);
603
604 If you are doing this sort of thing a lot, it can be worth adding a
605 custom type:
606
607 $ffi->attach( free_string => ['opaque'] => 'void' );
608 $ffi->custom_type( 'my_string' => {
609 native_type => 'opaque',
610 native_to_perl => sub {
611 my($ptr) = @_;
612 my $str = $ffi->cast( 'opaque' => 'string', $ptr ); # copies the string
613 free_string($ptr);
614 $str;
615 }
616 });
617
618 $ffi->attach( get_string => [] => 'my_string' );
619 my $str = get_string();
620
621 Since version 0.62, pointers and arrays to strings are supported as a
622 first class type. Prior to that L<FFI::Platypus::Type::StringArray>
623 and L<FFI::Platypus::Type::StringPointer> could be used, though their
624 use in new code is discouraged.
625
626 $ffi->attach( foo => ['string[]'] => 'void' );
627 foo( [ 'array', 'of', 'strings' ] );
628
629 $ffi->attach( bar => ['string*'] => 'void' );
630 my $string = 'baz';
631 bar( \$string ); # $string may be modified.
632
633 Strings are not allowed as return types from closure. This, again
634 is due to the ownership model of scalars in Perl. (There is no way
635 for Perl to know when calling language is done with the memory allocated
636 to the string). Consider the API:
637
638 typedef const char *(*get_message_t)(void);
639
640 void
641 print_message(get_message_t get_message)
642 {
643 const char *str;
644 str = get_message();
645 printf("message = %s\n", str);
646 }
647
648 It feels like this should be able to work:
649
650 $ffi->type('()->string' => 'get_message_t'); # not ok
651 $ffi->attach( print_message => ['get_message_t'] => 'void' );
652 my $get_message = $ffi->closure(sub {
653 return "my message";
654 });
655 print_message($get_message);
656
657 If the type declaration for C<get_message_t> were legal, then this
658 script would likely segfault or in the very least corrupt memory.
659 The problem is that once C<"my message"> is returned from the closure
660 Perl doesn't have a reference to it anymore and will free it.
661 To do this safely, you have to keep a reference to the scalar around
662 and return an opaque pointer to the string using a cast.
663
664 $ffi->type('()->opaque' => 'get_message_t');
665 $ffi->attach( print_message => ['get_message_t'] => 'void' );
666 my $get_message => $ffi->closure(sub {
667 our $message = "my message"; # needs to be our so that it doesn't
668 # get free'd
669 my $ptr = $ffi->cast('string' => 'opaque', $message);
670 return $ptr;
671 });
672 print_message($get_message);
673
674 Another type of string that you may run into with some APIs is the
675 so called "wide" string. In your C code if you see C<wchar_t*>
676 or C<const wchar_t*> or if in Win32 API code you see C<LPWSTR>
677 or C<LPCWSTR>. Most commonly you will see these types when working
678 with the Win32 API, but you may see them in Unix as well. These
679 types are intended for dealing with Unicode, but they do not use
680 the same UTF-8 format used by Perl internally, so they need to be
681 converted. You can do this manually by allocating the memory
682 and using the L<Encode> module, but the easier way is to use
683 either L<FFI::Platypus::Type::WideString> or
684 L<FFI::Platypus::Lang::Win32>, which handle the memory allocation
685 and conversion for you.
686
687 String types can be defined to have a fixed length using a trailing
688 parenthetical like so C<string(10)>. For arguments this has little
689 practical effect since the strings are passed as pointers anyway,
690 but does impact return values. If a function that returns a C<string(10)>
691 type returns a string that is not NULL terminated, only the first ten bytes
692 will be returned in the result.
693
694 Internally fixed length strings are implemented the same as
695 classless record types (that is to say C<string(10)> is identically
696 internally to C<record(10)*>).
697
698 For the 1.00 Platypus API, the C<string(10)> type was specified as
699 a pointer (that is C<string(10)*>). This was a mistake, but you
700 can still use the latter as an alias for the correct form in the
701 2.00 API.
702
703 =head2 Pointers and Arrays of Strings
704
705 As of the 1.00 Platypus API, you can specify pointers to strings
706 (C<string*>) and arrays of strings (C<string[10]>). Since strings
707 themselves are passed as pointers, this means these types are
708 passed in as pointers to pointers. If the pointer to the string
709 is changed then when the function returns the scalar or array
710 will be updated as well.
711
712 =head2 Pointer / References
713
714 In C you can pass a pointer to a variable to a function in order
715 accomplish the task of pass by reference. In Perl the same task is
716 accomplished by passing a reference (although you can also modify the
717 argument stack thus Perl supports proper pass by reference as well).
718
719 With L<FFI::Platypus> you can define a pointer to any native, string
720 or record type. You cannot (at least not yet) define a pointer to
721 a pointer or a pointer to an array or any other type not otherwise
722 supported. When passing in a pointer to something you must make sure
723 to pass in a reference to a scalar, or C<undef> (C<undef> will be
724 translated int C<NULL>).
725
726 If the C code makes a change to the value pointed to by the pointer, the
727 scalar will be updated before returning to Perl space. Example, with C
728 code.
729
730 /* foo.c */
731 void increment_int(int *value)
732 {
733 if(value != NULL)
734 (*value)++;
735 else
736 fprintf(stderr, "NULL pointer!\n");
737 }
738
739 # foo.pl
740 use FFI::Platypus 2.00;
741 my $ffi = FFI::Platypus->new( api => 2 );
742 $ffi->lib('libfoo.so'); # change to reflect the dynamic lib
743 # that contains foo.c
744 $ffi->type('int*' => 'int_p');
745 $ffi->attach(increment_int => ['int_p'] => 'void');
746 my $i = 0;
747 increment_int(\$i); # $i == 1
748 increment_int(\$i); # $i == 2
749 increment_int(\$i); # $i == 3
750 increment_int(undef); # prints "NULL pointer!\n"
751
752 Older versions of Platypus did not support pointers to strings or records.
753
754 =head2 Records
755
756 Records are structured data of a fixed length. In C they are called
757 C<struct>s.
758
759 For most C structured data, as long as you do not need to a record
760 by value, L<FFI::C> is the better choice. Briefly, L<FFI::C> supports
761 C<struct>, C<union>, and arrays of C<struct> and C<unions>. L<FFI::C>
762 does not support passing by value. The reminder of this section will
763 discuss only the C<record> type.
764
765 To declare a record type, use C<record>:
766
767 $ffi->type( 'record (42)' => 'my_record_of_size_42_bytes' );
768
769 The easiest way to mange records with Platypus is by using
770 L<FFI::Platypus::Record> to define a record layout for a record class.
771 Here is a brief example:
772
773 package Unix::TimeStruct;
774
775 use FFI::Platypus 2.00;
776 use FFI::Platypus::Record;
777
778 record_layout_1(qw(
779 int tm_sec
780 int tm_min
781 int tm_hour
782 int tm_mday
783 int tm_mon
784 int tm_year
785 int tm_wday
786 int tm_yday
787 int tm_isdst
788 long tm_gmtoff
789 string tm_zone
790 ));
791
792 my $ffi = FFI::Platypus->new( api => 2 );
793 $ffi->lib(undef);
794 # define a record class Unix::TimeStruct and alias it to "tm"
795 $ffi->type("record(Unix::TimeStruct)*" => 'tm');
796
797 # attach the C localtime function as a constructor
798 $ffi->attach( localtime => ['time_t*'] => 'tm', sub {
799 my($inner, $class, $time) = @_;
800 $time = time unless defined $time;
801 $inner->(\$time);
802 });
803
804 package main;
805
806 # now we can actually use our Unix::TimeStruct class
807 my $time = Unix::TimeStruct->localtime;
808 printf "time is %d:%d:%d %s\n",
809 $time->tm_hour,
810 $time->tm_min,
811 $time->tm_sec,
812 $time->tm_zone;
813
814 For more detailed usage, see L<FFI::Platypus::Record>.
815
816 Platypus does not manage the structure of a record (that is up to you),
817 it just keeps track of their size and makes sure that they are copied
818 correctly when used as a return type. A record in Perl is just a string
819 of bytes stored as a scalar. In addition to defining a record layout
820 for a record class, there are a number of tools you can use manipulate
821 records in Perl, two notable examples are L<pack and unpack|perlpacktut>
822 and L<Convert::Binary::C>.
823
824 Here is an example with commentary that uses L<Convert::Binary::C> to
825 extract the component time values from the C C<localtime> function, and
826 then smushes them back together to get the original C<time_t> (an
827 integer).
828
829 use Convert::Binary::C;
830 use FFI::Platypus 2.00;
831 use Data::Dumper qw( Dumper );
832
833 my $c = Convert::Binary::C->new;
834
835 # Alignment of zero (0) means use
836 # the alignment of your CPU
837 $c->configure( Alignment => 0 );
838
839 # parse the tm record structure so
840 # that Convert::Binary::C knows
841 # what to spit out and suck in
842 $c->parse(<<ENDC);
843 struct tm {
844 int tm_sec;
845 int tm_min;
846 int tm_hour;
847 int tm_mday;
848 int tm_mon;
849 int tm_year;
850 int tm_wday;
851 int tm_yday;
852 int tm_isdst;
853 long int tm_gmtoff;
854 const char *tm_zone;
855 };
856 ENDC
857
858 # get the size of tm so that we can give it
859 # to Platypus
860 my $tm_size = $c->sizeof("tm");
861
862 # create the Platypus instance and create the appropriate
863 # types and functions
864 my $ffi = FFI::Platypus->new( api => 2 );
865 $ffi->lib(undef);
866 $ffi->type("record($tm_size)*" => 'tm');
867 $ffi->attach( [ localtime => 'my_localtime' ] => ['time_t*'] => 'tm' );
868 $ffi->attach( [ time => 'my_time' ] => ['tm'] => 'time_t' );
869
870 # ===============================================
871 # get the tm struct from the C localtime function
872 # note that we pass in a reference to the value that time
873 # returns because localtime takes a pointer to time_t
874 # for some reason.
875 my $time_hashref = $c->unpack( tm => my_localtime(\time) );
876
877 # tm_zone comes back from Convert::Binary::C as an opaque,
878 # cast it into a string. We localize it to just this do
879 # block so that it will be a pointer when we pass it back
880 # to C land below.
881 do {
882 local $time_hashref->{tm_zone} = $ffi->cast(opaque => string => $time_hashref->{tm_zone});
883 print Dumper($time_hashref);
884 };
885
886 # ===============================================
887 # convert the tm struct back into an epoch value
888 my $time = my_time( $c->pack( tm => $time_hashref ) );
889
890 print "time = $time\n";
891 print "perl time = ", time, "\n";
892
893 You can also link a record type to a class. It will then be accepted
894 when blessed into that class as an argument passed into a C function,
895 and when it is returned from a C function it will be blessed into that
896 class. Basically:
897
898 $ffi->type( 'record(My::Class)*' => 'my_class' );
899 $ffi->attach( my_function1 => [ 'my_class' ] => 'void' );
900 $ffi->attach( my_function2 => [ ] => 'my_class' );
901
902 The only thing that your class MUST provide is either a
903 C<ffi_record_size> or C<_ffi_record_size> class method that returns the
904 size of the record in bytes.
905
906 Contrast a record type which is stored as a scalar string of bytes in
907 Perl to an opaque pointer which is stored as an integer in Perl. Both
908 are treated as pointers in C functions. The situations when you usually
909 want to use a record are when you know ahead of time what the size of
910 the object that you are working with and probably something about its
911 structure. Because a function that returns a structure copies the
912 structure into a Perl data structure, you want to make sure that it is
913 okay to copy the record objects that you are dealing with if any of your
914 functions will be returning one of them.
915
916 Opaque pointers should be used when you do not know the size of the
917 object that you are using, or if the objects are created and free'd
918 through an API interface other than C<malloc> and C<free>.
919
920 The examples in this section actually use pointers to records (note
921 the trailing star C<*> in the declarations). Most programming languages
922 allow you to pass or return a record as either pass-by-value or as a
923 pointer (pass-by-reference).
924
925 C code:
926
927 struct { int a; } foo_t;
928 void pass_by_value_example( struct foo_t foo );
929 void pass_by_reference_example( struct foo_t *foo );
930
931 Perl code:
932
933 {
934 package Foo;
935 use FFI::Platypus::Record;
936 record_layout_1( int => 'a' );
937 }
938 $ffi->type( 'Record(Foo)' => 'foo_t' );
939 $ffi->attach( pass_by_value_example => [ 'foo_t' ] => 'void' );
940 $ffi->attach( pass_by_reference_example => [ 'foo_t*' ] => 'void' );
941
942 As with strings, functions that return a pointer to a record are actually
943 copied.
944
945 C code:
946
947 struct foo_t *return_struct_pointer_example();
948
949 Perl code:
950
951 $ffi->attach( return_struct_pointer_example => [] => 'foo_t*' );
952 my $foo = return_struct_pointer_example();
953 # $foo is a copy of the record returned by the function.
954
955 As with strings, if the API expects you to free the record it returns
956 (it is misbehaving a little, but lets set that aside), then you can
957 work around this by returning an C<opaque> type, casting to the
958 record, and finally freeing the original pointer.
959
960 use FFI::Platypus::Memory qw( free );
961 $ffi->attach( return_struct_pointer_example => [] => 'opaque' );
962 my $foo_ptr = return_struct_pointer_example();
963 my $foo = $ffi->cast( 'opaque' => 'foo_t*', $foo_ptr );
964 free $foo_ptr;
965
966 You can pass records into a closure, but care needs to be taken.
967 Records passed into a closure are read-only inside the closure,
968 including C<string rw> members. Although you can pass a "pointer"
969 to a record into a closure, because of limitations of the
970 implementation you actually have a copy, so all records passed
971 into closures are passed by-value.
972
973 Note that a record that does not have a class (classless) and is
974 defined instead using a length is internally identical to fixed
975 strings. That is to say C<string(10)> and C<record(10)*> are
976 identical.
977
978 =head2 Fixed length arrays
979
980 Fixed length arrays of native types and strings are supported by
981 L<FFI::Platypus>. Like pointers, if the values contained in the
982 array are updated by the C function these changes will be reflected
983 when it returns to Perl space. An example of using this is the
984 Unix C<pipe> command which returns a list of two file descriptors
985 as an array.
986
987 use FFI::Platypus 2.00;
988
989 my $ffi = FFI::Platypus->new( api => 2 );
990 $ffi->lib(undef);
991 $ffi->attach([pipe=>'mypipe'] => ['int[2]'] => 'int');
992
993 my @fd = (0,0);
994 mypipe(\@fd);
995 my($fd1,$fd2) = @fd;
996
997 print "$fd1 $fd2\n";
998
999 Because of the way records are implemented, an array of records
1000 does not make sense and is not currently supported.
1001
1002 =head2 Variable length arrays
1003
1004 [version 0.22]
1005
1006 Variable length arrays are supported for argument types can also be
1007 specified by using the C<[]> notation but by leaving the size empty:
1008
1009 $ffi->type('int[]' => 'var_int_array');
1010
1011 When used as an argument type it will probe the array reference that you
1012 pass in to determine the correct size. Usually you will need to
1013 communicate the size of the array to the C code. One way to do this is
1014 to pass the length of the array in as an additional argument. For
1015 example the C code:
1016
1017 int
1018 sum(int *array, int size)
1019 {
1020 int total, i;
1021 for (i = 0, total = 0; i < size; i++)
1022 {
1023 total += array[i];
1024 }
1025 return total;
1026 }
1027
1028 Can be called from Perl like this:
1029
1030 use FFI::Platypus 2.00;
1031
1032 my $ffi = FFI::Platypus->new( api => 2 );
1033 $ffi->lib('./var_array.so');
1034
1035 $ffi->attach( sum => [ 'int[]', 'int' ] => 'int' );
1036
1037 my @list = (1..100);
1038
1039 print sum(\@list, scalar @list), "\n";
1040
1041 Another method might be to have a special value, such as 0 or NULL
1042 indicate the termination of the array.
1043
1044 Because of the way records are implemented, an array of records
1045 does not make sense and is not currently supported.
1046
1047 =head2 Closures
1048
1049 A closure (sometimes called a "callback", we use the C<libffi>
1050 terminology) is a Perl subroutine that can be called from C. In order
1051 to be called from C it needs to be passed to a C function. To define
1052 the closure type you need to provide a list of argument types and a
1053 return type. Currently only native types (integers, floating point
1054 values, opaque), strings and records (by-value; you can pass a pointer
1055 to a record, but due to limitations of the record implementation this
1056 is actually a copy) are supported as closure argument types, and only
1057 native types and records (by-value; pointer records and records with
1058 string pointers cannot be returned from a closure) are supported as
1059 closure return types. Inside the closure any records passed in are
1060 read-only.
1061
1062 We plan to add other types, though they can be converted using the Platypus
1063 C<cast> or C<attach_cast> methods.
1064
1065 Here is an example, with C code:
1066
1067 /*
1068 * closure.c - on Linux compile with: gcc closure.c -shared -o closure.so -fPIC
1069 */
1070
1071 #include <stdio.h>
1072
1073 typedef int (*closure_t)(int);
1074 closure_t my_closure = NULL;
1075
1076 void set_closure(closure_t value)
1077 {
1078 my_closure = value;
1079 }
1080
1081 int call_closure(int value)
1082 {
1083 if(my_closure != NULL)
1084 return my_closure(value);
1085 else
1086 fprintf(stderr, "closure is NULL\n");
1087 }
1088
1089 And the Perl code:
1090
1091 use FFI::Platypus 2.00;
1092
1093 my $ffi = FFI::Platypus->new( api => 2 );
1094 $ffi->lib('./closure.so');
1095 $ffi->type('(int)->int' => 'closure_t');
1096
1097 $ffi->attach(set_closure => ['closure_t'] => 'void');
1098 $ffi->attach(call_closure => ['int'] => 'int');
1099
1100 my $closure1 = $ffi->closure(sub { $_[0] * 2 });
1101 set_closure($closure1);
1102 print call_closure(2), "\n"; # prints "4"
1103
1104 my $closure2 = $ffi->closure(sub { $_[0] * 4 });
1105 set_closure($closure2);
1106 print call_closure(2), "\n"; # prints "8"
1107
1108 If you have a pointer to a function in the form of an C<opaque> type,
1109 you can pass this in place of a closure type:
1110
1111 use FFI::Platypus 2.00;
1112
1113 my $ffi = FFI::Platypus->new( api => 2 );
1114 $ffi->lib('./closure.so');
1115 $ffi->type('(int)->int' => 'closure_t');
1116
1117 $ffi->attach(set_closure => ['closure_t'] => 'void');
1118 $ffi->attach(call_closure => ['int'] => 'int');
1119
1120 my $closure = $ffi->closure(sub { $_[0] * 6 });
1121 my $opaque = $ffi->cast(closure_t => 'opaque', $closure);
1122 set_closure($opaque);
1123 print call_closure(2), "\n"; # prints "12"
1124
1125 The syntax for specifying a closure type is a list of comma separated
1126 types in parentheticals followed by a narrow arrow C<-E<gt>>, followed
1127 by the return type for the closure. For example a closure that takes a
1128 pointer, an integer and a string and returns an integer would look like
1129 this:
1130
1131 $ffi->type('(opaque, int, string) -> int' => 'my_closure_type');
1132
1133 Care needs to be taken with scoping and closures, because of the way
1134 Perl and C handle responsibility for allocating memory differently.
1135 Perl keeps reference counts and frees objects when nothing is
1136 referencing them. In C the code that allocates the memory is considered
1137 responsible for explicitly free'ing the memory for objects it has
1138 created when they are no longer needed. When you pass a closure into a
1139 C function, the C code has a pointer or reference to that object, but it
1140 has no way up letting Perl know when it is no longer using it. As a
1141 result, if you do not keep a reference to your closure around it will be
1142 free'd by Perl and if the C code ever tries to call the closure it will
1143 probably SIGSEGV. Thus supposing you have a C function C<set_closure>
1144 that takes a Perl closure, this is almost always wrong:
1145
1146 set_closure($ffi->closure({ $_[0] * 2 })); # BAD
1147
1148 In some cases, you may want to create a closure shouldn't ever be
1149 free'd. For example you are passing a closure into a C function that
1150 will retain it for the lifetime of your application. You can use the
1151 sticky method to keep the closure, without the need to keep a reference
1152 of the closure:
1153
1154 {
1155 my $closure = $ffi->closure(sub { $_[0] * 2 });
1156 $closure->sticky;
1157 set_closure($closure); # OKAY
1158 }
1159 # closure still exists and is accesible from C, but
1160 # not from Perl land.
1161
1162 =head2 Custom Types
1163
1164 =head3 Custom Types in Perl
1165
1166 Platypus custom types are the rough analogue to typemaps in the XS
1167 world. They offer a method for converting Perl types into native types
1168 that the C<libffi> can understand and pass on to the C code.
1169
1170 =head4 Example 1: Integer constants
1171
1172 Say you have a C header file like this:
1173
1174 /* possible foo types: */
1175 #define FOO_STATIC 1
1176 #define FOO_DYNAMIC 2
1177 #define FOO_OTHER 3
1178
1179 typedef int foo_t;
1180
1181 void foo(foo_t foo);
1182 foo_t get_foo();
1183
1184 The challenge is here that once the source is processed by the C
1185 pre-processor the name/value mappings for these C<FOO_> constants
1186 are lost. There is no way to fetch them from the library once it
1187 is compiled and linked.
1188
1189 One common way of implementing this would be to create and export
1190 constants in your Perl module, like this:
1191
1192 package Foo;
1193
1194 use FFI::Platypus 2.00;
1195 use Exporter qw( import );
1196
1197 our @EXPORT_OK = qw( FOO_STATIC FOO_DYNAMIC FOO_OTHER foo get_foo );
1198
1199 use constant FOO_STATIC => 1;
1200 use constant FOO_DYNAMIC => 2;
1201 use constant FOO_OTHER => 3;
1202
1203 my $ffi = FFI::Platypus->new( api => 2 );
1204 $ffi->attach(foo => ['int'] => 'void');
1205 $ffi->attach(get_foo => [] => 'int');
1206
1207 Then you could use the module thus:
1208
1209 use Foo qw( foo FOO_STATIC );
1210 foo(FOO_STATIC);
1211
1212 If you didn't want to rely on integer constants or exports, you could
1213 also define a custom type, and allow strings to be passed into your
1214 function, like this:
1215
1216 package Foo;
1217
1218 use FFI::Platypus 2.00;
1219
1220 our @EXPORT_OK = qw( foo get_foo );
1221
1222 my %foo_types = (
1223 static => 1,
1224 dynamic => 2,
1225 other => 3,
1226 );
1227 my %foo_types_reverse = reverse %foo_types;
1228
1229 my $ffi = FFI::Platypus->new( api => 2 );
1230 $ffi->custom_type(foo_t => {
1231 native_type => 'int',
1232 native_to_perl => sub {
1233 $foo_types{$_[0]};
1234 },
1235 perl_to_native => sub {
1236 $foo_types_reverse{$_[0]};
1237 },
1238 });
1239
1240 $ffi->attach(foo => ['foo_t'] => 'void');
1241 $ffi->attach(get_foo => [] => 'foo_t');
1242
1243 Now when an argument of type C<foo_t> is called for it will be converted
1244 from an appropriate string representation, and any function that returns
1245 a C<foo_t> type will return a string instead of the integer
1246 representation:
1247
1248 use Foo;
1249 foo('static');
1250
1251 If the library that you are using has a lot of these constants you can
1252 try using L<Convert::Binary::C> or another C header parser to obtain
1253 the appropriate name/value pairings for the constants that you need.
1254
1255 =head4 Example 2: Blessed references
1256
1257 Supposing you have a C library that uses an opaque pointer with a pseudo
1258 OO interface, like this:
1259
1260 typedef struct foo_t;
1261
1262 foo_t *foo_new();
1263 void foo_method(foo_t *, int argument);
1264 void foo_free(foo_t *);
1265
1266 One approach to adapting this to Perl would be to create a OO Perl
1267 interface like this:
1268
1269 package Foo;
1270
1271 use FFI::Platypus 2.00;
1272 use FFI::Platypus::API qw( arguments_get_string );
1273
1274 my $ffi = FFI::Platypus->new( api => 2 );
1275 $ffi->custom_type(foo_t => {
1276 native_type => 'opaque',
1277 native_to_perl => sub {
1278 my $class = arguments_get_string(0);
1279 bless \$_[0], $class;
1280 }
1281 perl_to_native => sub { ${$_[0]} },
1282 });
1283
1284 $ffi->attach([ foo_new => 'new' ] => [ 'string' ] => 'foo_t' );
1285 $ffi->attach([ foo_method => 'method' ] => [ 'foo_t', 'int' ] => 'void');
1286 $ffi->attach([ foo_free => 'DESTROY' ] => [ 'foo_t' ] => 'void');
1287
1288 my $foo = Foo->new;
1289
1290 Here we are blessing a reference to the opaque pointer when we return
1291 the custom type for C<foo_t>, and dereferencing that reference before we
1292 pass it back in. The function C<arguments_get_string> queries the C
1293 arguments to get the class name to make sure the object is blessed into
1294 the correct class (for more details on the custom type API see
1295 L<FFI::Platypus::API>), so you can inherit and extend this class like a
1296 normal Perl class. This works because the C "constructor" ignores the
1297 class name that we pass in as the first argument. If you have a C
1298 "constructor" like this that takes arguments you'd have to write a
1299 wrapper for new.
1300
1301 A good example of a C library that uses this pattern, including
1302 inheritance is C<libarchive>. Platypus comes with a more extensive
1303 example in C<examples/archive.pl> that demonstrates this.
1304
1305 =head4 Example 3: Pointers with pack / unpack
1306
1307 TODO
1308
1309 See example L<FFI::Platypus::Type::StringPointer>.
1310
1311 =head4 Example 4: Custom Type modules and the Custom Type API
1312
1313 TODO
1314
1315 See example L<FFI::Platypus::Type::PointerSizeBuffer>.
1316
1317 =head4 Example 5: Custom Type on CPAN
1318
1319 You can distribute your own Platypus custom types on CPAN, if you think
1320 they may be applicable to others. The default namespace is prefix with
1321 C<FFI::Platypus::Type::>, though you can stick it anywhere (under your
1322 own namespace may make more sense if the custom type is specific to your
1323 application).
1324
1325 A good example and pattern to follow is
1326 L<FFI::Platypus::Type::StringArray>.
1327
1328 =head1 SEE ALSO
1329
1330 =over 4
1331
1332 =item L<FFI::Platypus>
1333
1334 Main platypus documentation.
1335
1336 =item L<FFI::Platypus::API>
1337
1338 Custom types API.
1339
1340 =item L<FFI::Platypus::Type::StringPointer>
1341
1342 String pointer type.
1343
1344 =back
1345
1346 =head1 AUTHOR
1347
1348 Author: Graham Ollis E<lt>[email protected]<gt>
1349
1350 Contributors:
1351
1352 Bakkiaraj Murugesan (bakkiaraj)
1353
1354 Dylan Cali (calid)
1355
1356 pipcet
1357
1358 Zaki Mughal (zmughal)
1359
1360 Fitz Elliott (felliott)
1361
1362 Vickenty Fesunov (vyf)
1363
1364 Gregor Herrmann (gregoa)
1365
1366 Shlomi Fish (shlomif)
1367
1368 Damyan Ivanov
1369
1370 Ilya Pavlov (Ilya33)
1371
1372 Petr Písař (ppisar)
1373
1374 Mohammad S Anwar (MANWAR)
1375
1376 Håkon Hægland (hakonhagland, HAKONH)
1377
1378 Meredith (merrilymeredith, MHOWARD)
1379
1380 Diab Jerius (DJERIUS)
1381
1382 Eric Brine (IKEGAMI)
1383
1384 szTheory
1385
1386 José Joaquín Atria (JJATRIA)
1387
1388 Pete Houston (openstrike, HOUSTON)
1389
1390 Lukas Mai (MAUKE)
1391
1392 =head1 COPYRIGHT AND LICENSE
1393
1394 This software is copyright (c) 2015-2022 by Graham Ollis.
1395
1396 This is free software; you can redistribute it and/or modify it under
1397 the same terms as the Perl 5 programming language system itself.
1398
1399 =cut