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