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.58
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 For functions that take a pointer to a void pointer (that is a "void
399 **"), you can use a pointer to an opaque type. Consider the C code:
400
401 struct archive_entry;
402 int archive_read_next_header(struct archive *, struvct archive_entry **);
403
404 Once again the internals of "archive_entry" are not provided. Perl
405 code:
406
407 $ffi->type('opaque' => 'archive_entry');
408 $ffi->attach(archive_read_next_header => [ 'archive', 'archive_entry*' ] => 'int');
409
410 Now we can call this function
411
412 my $archive = archive_read_new();
413 ... # additional prep for $active is required
414 while(1) {
415 my $entry;
416 archive_read_next_header($archive, \$entry);
417 last unless defined $entry;
418 # can now use $entry for other archive_entry_ methods.
419 }
420
421 The way "archive_read_next_header" works, it will return a pointer to
422 the next "archive_entry" object until it gets to the end, when it will
423 return a pointer to "NULL" which will be represented in Perl by a
424 "undef".
425
426 There are a number of useful utility functions for dealing with opaque
427 types in the FFI::Platypus::Memory module.
428
429 Objects
430 Object types are thin wrappers around two native types: integer and
431 "opaque" types. They are just blessed references around either of
432 those two types so that methods can be defined on them, but when they
433 get passed to a Platypus xsub they are converted into the native
434 integer or "opaque" types. This type is most useful when a API
435 provides an OO style interface with an integer or "opaque" value acting
436 as an instance of a class. There are two detailed examples in the main
437 Platypus documentation using libarchive and unix open:
438
439 "libarchive" in FFI::Platypus
440 "unix open" in FFI::Platypus
441
442 Strings
443 From the CPU's perspective, strings are just pointers. From Perl and
444 C's perspective, those pointers point to a series of characters. For C
445 they are null terminates ("\0"). FFI::Platypus handles the details
446 where they differ. Basically when you see "char *" or "const char *"
447 used in a C header file you can expect to be able to use the "string"
448 type.
449
450 $ffi->attach( puts => [ 'string' ] => 'int' );
451
452 The pointer passed into C (or other language) is to the content of the
453 actual scalar, which means it can modify the content of a scalar.
454
455 NOTE: When used as a return type, the string is copied into a new
456 scalar rather than using the original address. This is due to the
457 ownership model of scalars in Perl, but it is also most of the time
458 what you want.
459
460 This can be problematic when a function returns a string that the
461 callee is expected to free. Consider the functions:
462
463 char *
464 get_string()
465 {
466 char *buffer;
467 buffer = malloc(20);
468 strcpy(buffer, "Perl");
469 }
470
471 void
472 free_string(char *buffer)
473 {
474 free(buffer);
475 }
476
477 This API returns a string that you are expected to free when you are
478 done with it. (At least they have provided an API for freeing the
479 string instead of expecting you to call libc free)! A simple binding
480 to get the string would be:
481
482 $ffi->attach( get_string => [] => 'string' ); # memory leak
483 my $str = get_string();
484
485 Which will work to a point, but the memory allocated by get_string will
486 leak. Instead you need to get the opaque pointer, cast it to a string
487 and then free it.
488
489 $ffi->attach( get_string => [] => 'opaque' );
490 $ffi->attach( free_string => ['opaque'] => 'void' );
491 my $ptr = get_string();
492 my $str = $ffi->cast( 'opaque' => 'string', $ptr ); # copies the string
493 free_string($ptr);
494
495 If you are doing this sort of thing a lot, it can be worth adding a
496 custom type:
497
498 $ffi->attach( free_string => ['opaque'] => 'void' );
499 $ffi->custom_type( 'my_string' => {
500 native_type => 'opaque',
501 native_to_perl => sub {
502 my($ptr) = @_;
503 my $str = $ffi->cast( 'opaque' => 'string', $ptr ); # copies the string
504 free_string($ptr);
505 $str;
506 }
507 });
508
509 $ffi->attach( get_string => [] => 'my_string' );
510 my $str = get_string();
511
512 Since version 0.62, pointers and arrays to strings are supported as a
513 first class type. Prior to that FFI::Platypus::Type::StringArray and
514 FFI::Platypus::Type::StringPointer could be used, though their use in
515 new code is discouraged.
516
517 $ffi->attach( foo => ['string[]'] => 'void' );
518 foo( [ 'array', 'of', 'strings' ] );
519
520 $ffi->attach( bar => ['string*'] => 'void' );
521 my $string = 'baz';
522 bar( \$string ); # $string may be modified.
523
524 Strings are not allowed as return types from closure. This, again is
525 due to the ownership model of scalars in Perl. (There is no way for
526 Perl to know when calling language is done with the memory allocated to
527 the string). Consider the API:
528
529 typedef const char *(*get_message_t)(void);
530
531 void
532 print_message(get_message_t get_message)
533 {
534 const char *str;
535 str = get_message();
536 printf("message = %s\n", str);
537 }
538
539 It feels like this should be able to work:
540
541 $ffi->type('()->string' => 'get_message_t'); # not ok
542 $ffi->attach( print_message => ['get_message_t'] => 'void' );
543 my $get_message = $ffi->closure(sub {
544 return "my message";
545 });
546 print_message($get_message);
547
548 If the type declaration for "get_message_t" were legal, then this
549 script would likely segfault or in the very least corrupt memory. The
550 problem is that once "my message" is returned from the closure Perl
551 doesn't have a reference to it anymore and will free it. To do this
552 safely, you have to keep a reference to the scalar around and return an
553 opaque pointer to the string using a cast.
554
555 $ffi->type('()->opaque' => 'get_message_t');
556 $ffi->attach( print_message => ['get_message_t'] => 'void' );
557 my $get_message => $ffi->closure(sub {
558 our $message = "my message"; # needs to be our so that it doesn't
559 # get free'd
560 my $ptr = $ffi->cast('string' => 'opaque', $message);
561 return $ptr;
562 });
563 print_message($get_message);
564
565 Another type of string that you may run into with some APIs is the so
566 called "wide" string. In your C code if you see "wchar_t*" or "const
567 wchar_t*" or if in Win32 API code you see "LPWSTR" or "LPCWSTR". Most
568 commonly you will see these types when working with the Win32 API, but
569 you may see them in Unix as well. These types are intended for dealing
570 with Unicode, but they do not use the same UTF-8 format used by Perl
571 internally, so they need to be converted. You can do this manually by
572 allocating the memory and using the Encode module, but the easier way
573 is to use either FFI::Platypus::Type::WideString or
574 FFI::Platypus::Lang::Win32, which handle the memory allocation and
575 conversion for you.
576
577 Pointer / References
578 In C you can pass a pointer to a variable to a function in order
579 accomplish the task of pass by reference. In Perl the same task is
580 accomplished by passing a reference (although you can also modify the
581 argument stack thus Perl supports proper pass by reference as well).
582
583 With FFI::Platypus you can define a pointer to any native, string or
584 record type. You cannot (at least not yet) define a pointer to a
585 pointer or a pointer to an array or any other type not otherwise
586 supported. When passing in a pointer to something you must make sure
587 to pass in a reference to a scalar, or "undef" ("undef" will be
588 translated int "NULL").
589
590 If the C code makes a change to the value pointed to by the pointer,
591 the scalar will be updated before returning to Perl space. Example,
592 with C code.
593
594 /* foo.c */
595 void increment_int(int *value)
596 {
597 if(value != NULL)
598 (*value)++;
599 else
600 fprintf(stderr, "NULL pointer!\n");
601 }
602
603 # foo.pl
604 use FFI::Platypus 1.00;
605 my $ffi = FFI::Platypus->new( api => 1 );
606 $ffi->lib('libfoo.so'); # change to reflect the dynamic lib
607 # that contains foo.c
608 $ffi->type('int*' => 'int_p');
609 $ffi->attach(increment_int => ['int_p'] => 'void');
610 my $i = 0;
611 increment_int(\$i); # $i == 1
612 increment_int(\$i); # $i == 2
613 increment_int(\$i); # $i == 3
614 increment_int(undef); # prints "NULL pointer!\n"
615
616 Older versions of Platypus did not support pointers to strings or
617 records.
618
619 Records
620 Records are structured data of a fixed length. In C they are called
621 "struct"s.
622
623 The Platypus native way of working with structured data is via the
624 "record" type. There is also FFI::C which has some overlapping
625 functionality. Briefly, FFI::C supports "union" and arrays of
626 structured types, but not passing structured data by-value, while the
627 "record" type doesn't support "union" or arrays of structured data, but
628 does support passing structured data by-value. The remainder of this
629 section will discuss the native Platypus "record" type, but you should
630 remember that for some applications FFI::C might be more appropriate.
631
632 To declare a record type, use "record":
633
634 $ffi->type( 'record (42)' => 'my_record_of_size_42_bytes' );
635
636 The easiest way to mange records with Platypus is by using
637 FFI::Platypus::Record to define a record layout for a record class.
638 Here is a brief example:
639
640 package Unix::TimeStruct;
641
642 use FFI::Platypus 1.00;
643 use FFI::Platypus::Record;
644
645 record_layout_1(qw(
646 int tm_sec
647 int tm_min
648 int tm_hour
649 int tm_mday
650 int tm_mon
651 int tm_year
652 int tm_wday
653 int tm_yday
654 int tm_isdst
655 long tm_gmtoff
656 string tm_zone
657 ));
658
659 my $ffi = FFI::Platypus->new( api => 1 );
660 $ffi->lib(undef);
661 # define a record class Unix::TimeStruct and alias it to "tm"
662 $ffi->type("record(Unix::TimeStruct)*" => 'tm');
663
664 # attach the C localtime function as a constructor
665 $ffi->attach( localtime => ['time_t*'] => 'tm', sub {
666 my($inner, $class, $time) = @_;
667 $time = time unless defined $time;
668 $inner->(\$time);
669 });
670
671 package main;
672
673 # now we can actually use our Unix::TimeStruct class
674 my $time = Unix::TimeStruct->localtime;
675 printf "time is %d:%d:%d %s\n",
676 $time->tm_hour,
677 $time->tm_min,
678 $time->tm_sec,
679 $time->tm_zone;
680
681 For more detailed usage, see FFI::Platypus::Record.
682
683 Platypus does not manage the structure of a record (that is up to you),
684 it just keeps track of their size and makes sure that they are copied
685 correctly when used as a return type. A record in Perl is just a
686 string of bytes stored as a scalar. In addition to defining a record
687 layout for a record class, there are a number of tools you can use
688 manipulate records in Perl, two notable examples are pack and unpack
689 and Convert::Binary::C.
690
691 Here is an example with commentary that uses Convert::Binary::C to
692 extract the component time values from the C "localtime" function, and
693 then smushes them back together to get the original "time_t" (an
694 integer).
695
696 use Convert::Binary::C;
697 use FFI::Platypus 1.00;
698 use Data::Dumper qw( Dumper );
699
700 my $c = Convert::Binary::C->new;
701
702 # Alignment of zero (0) means use
703 # the alignment of your CPU
704 $c->configure( Alignment => 0 );
705
706 # parse the tm record structure so
707 # that Convert::Binary::C knows
708 # what to spit out and suck in
709 $c->parse(<<ENDC);
710 struct tm {
711 int tm_sec;
712 int tm_min;
713 int tm_hour;
714 int tm_mday;
715 int tm_mon;
716 int tm_year;
717 int tm_wday;
718 int tm_yday;
719 int tm_isdst;
720 long int tm_gmtoff;
721 const char *tm_zone;
722 };
723 ENDC
724
725 # get the size of tm so that we can give it
726 # to Platypus
727 my $tm_size = $c->sizeof("tm");
728
729 # create the Platypus instance and create the appropriate
730 # types and functions
731 my $ffi = FFI::Platypus->new( api => 1 );
732 $ffi->lib(undef);
733 $ffi->type("record($tm_size)*" => 'tm');
734 $ffi->attach( [ localtime => 'my_localtime' ] => ['time_t*'] => 'tm' );
735 $ffi->attach( [ time => 'my_time' ] => ['tm'] => 'time_t' );
736
737 # ===============================================
738 # get the tm struct from the C localtime function
739 # note that we pass in a reference to the value that time
740 # returns because localtime takes a pointer to time_t
741 # for some reason.
742 my $time_hashref = $c->unpack( tm => my_localtime(\time) );
743
744 # tm_zone comes back from Convert::Binary::C as an opaque,
745 # cast it into a string. We localize it to just this do
746 # block so that it will be a pointer when we pass it back
747 # to C land below.
748 do {
749 local $time_hashref->{tm_zone} = $ffi->cast(opaque => string => $time_hashref->{tm_zone});
750 print Dumper($time_hashref);
751 };
752
753 # ===============================================
754 # convert the tm struct back into an epoch value
755 my $time = my_time( $c->pack( tm => $time_hashref ) );
756
757 print "time = $time\n";
758 print "perl time = ", time, "\n";
759
760 You can also link a record type to a class. It will then be accepted
761 when blessed into that class as an argument passed into a C function,
762 and when it is returned from a C function it will be blessed into that
763 class. Basically:
764
765 $ffi->type( 'record(My::Class)*' => 'my_class' );
766 $ffi->attach( my_function1 => [ 'my_class' ] => 'void' );
767 $ffi->attach( my_function2 => [ ] => 'my_class' );
768
769 The only thing that your class MUST provide is either a
770 "ffi_record_size" or "_ffi_record_size" class method that returns the
771 size of the record in bytes.
772
773 Here is a longer practical example, once again using the tm struct:
774
775 package Unix::TimeStruct;
776
777 use FFI::Platypus 1.00;
778 use FFI::TinyCC;
779 use FFI::TinyCC::Inline 'tcc_eval';
780
781 # store the source of the tm struct
782 # for repeated use later
783 my $tm_source = <<ENDTM;
784 struct tm {
785 int tm_sec;
786 int tm_min;
787 int tm_hour;
788 int tm_mday;
789 int tm_mon;
790 int tm_year;
791 int tm_wday;
792 int tm_yday;
793 int tm_isdst;
794 long int tm_gmtoff;
795 const char *tm_zone;
796 };
797 ENDTM
798
799 # calculate the size of the tm struct
800 # this time using Tiny CC
801 my $tm_size = tcc_eval qq{
802 $tm_source
803 int main()
804 {
805 return sizeof(struct tm);
806 }
807 };
808
809 # To use Unix::TimeStruct as a record class, we need to
810 # specify a size for the record, a function called
811 # either ffi_record_size or _ffi_record_size should
812 # return the size in bytes. This function has to
813 # be defined before you try to define it as a type.
814 sub _ffi_record_size { $tm_size };
815
816 my $ffi = FFI::Platypus->new( api => 1 );
817 $ffi->lib(undef);
818 # define a record class Unix::TimeStruct and alias it
819 # to "tm"
820 $ffi->type("record(Unix::TimeStruct)*" => 'tm');
821
822 # attach the C localtime function as a constructor
823 $ffi->attach( [ localtime => '_new' ] => ['time_t*'] => 'tm' );
824
825 # the constructor needs to be wrapped in a Perl sub,
826 # because localtime is expecting the time_t (if provided)
827 # to come in as the first argument, not the second.
828 # We could also acomplish something similar using
829 # custom types.
830 sub new { _new(\($_[1] || time)) }
831
832 # for each attribute that we are interested in, create
833 # get and set accessors. We just make accessors for
834 # hour, minute and second, but we could make them for
835 # all the fields if we needed.
836 foreach my $attr (qw( hour min sec ))
837 {
838 my $tcc = FFI::TinyCC->new;
839 $tcc->compile_string(qq{
840 $tm_source
841 int
842 get_$attr (struct tm *tm)
843 {
844 return tm->tm_$attr;
845 }
846 void
847 set_$attr (struct tm *tm, int value)
848 {
849 tm->tm_$attr = value;
850 }
851 });
852 $ffi->attach( [ $tcc->get_symbol("get_$attr") => "get_$attr" ] => [ 'tm' ] => 'int' );
853 $ffi->attach( [ $tcc->get_symbol("set_$attr") => "set_$attr" ] => [ 'tm' ] => 'int' );
854 }
855
856 package main;
857
858 # now we can actually use our Unix::TimeStruct class
859 my $time = Unix::TimeStruct->new;
860 printf "time is %d:%d:%d\n", $time->get_hour, $time->get_min, $time->get_sec;
861
862 Contrast a record type which is stored as a scalar string of bytes in
863 Perl to an opaque pointer which is stored as an integer in Perl. Both
864 are treated as pointers in C functions. The situations when you
865 usually want to use a record are when you know ahead of time what the
866 size of the object that you are working with and probably something
867 about its structure. Because a function that returns a structure
868 copies the structure into a Perl data structure, you want to make sure
869 that it is okay to copy the record objects that you are dealing with if
870 any of your functions will be returning one of them.
871
872 Opaque pointers should be used when you do not know the size of the
873 object that you are using, or if the objects are created and free'd
874 through an API interface other than "malloc" and "free".
875
876 The examples in this section actually use pointers to records (note the
877 trailing star "*" in the declarations). Most programming languages
878 allow you to pass or return a record as either pass-by-value or as a
879 pointer (pass-by-reference).
880
881 C code:
882
883 struct { int a; } foo_t;
884 void pass_by_value_example( struct foo_t foo );
885 void pass_by_reference_example( struct foo_t *foo );
886
887 Perl code:
888
889 {
890 package Foo;
891 use FFI::Platypus::Record;
892 record_layout_1( int => 'a' );
893 }
894 $ffi->type( 'Record(Foo)' => 'foo_t' );
895 $ffi->attach( pass_by_value_example => [ 'foo_t' ] => 'void' );
896 $ffi->attach( pass_by_reference_example => [ 'foo_t*' ] => 'void' );
897
898 As with strings, functions that return a pointer to a record are
899 actually copied.
900
901 C code:
902
903 struct foo_t *return_struct_pointer_example();
904
905 Perl code:
906
907 $ffi->attach( return_struct_pointer_example => [] => 'foo_t*' );
908 my $foo = return_struct_pointer_example();
909 # $foo is a copy of the record returned by the function.
910
911 As with strings, if the API expects you to free the record it returns
912 (it is misbehaving a little, but lets set that aside), then you can
913 work around this by returning an "opaque" type, casting to the record,
914 and finally freeing the original pointer.
915
916 use FFI::Platypus::Memory qw( free );
917 $ffi->attach( return_struct_pointer_example => [] => 'opaque' );
918 my $foo_ptr = return_struct_pointer_example();
919 my $foo = $ffi->cast( 'opaque' => 'foo_t*', $foo_ptr );
920 free $foo_ptr;
921
922 You can pass records into a closure, but care needs to be taken.
923 Records passed into a closure are read-only inside the closure,
924 including "string rw" members. Although you can pass a "pointer" to a
925 record into a closure, because of limitations of the implementation you
926 actually have a copy, so all records passed into closures are passed
927 by-value.
928
929 Fixed length arrays
930 Fixed length arrays of native types and strings are supported by
931 FFI::Platypus. Like pointers, if the values contained in the array are
932 updated by the C function these changes will be reflected when it
933 returns to Perl space. An example of using this is the Unix "pipe"
934 command which returns a list of two file descriptors as an array.
935
936 use FFI::Platypus 1.00;
937
938 my $ffi = FFI::Platypus->new( api => 1 );
939 $ffi->lib(undef);
940 $ffi->attach([pipe=>'mypipe'] => ['int[2]'] => 'int');
941
942 my @fd = (0,0);
943 mypipe(\@fd);
944 my($fd1,$fd2) = @fd;
945
946 print "$fd1 $fd2\n";
947
948 Because of the way records are implemented, an array of records does
949 not make sense and is not currently supported.
950
951 Variable length arrays
952 [version 0.22]
953
954 Variable length arrays are supported for argument types can also be
955 specified by using the "[]" notation but by leaving the size empty:
956
957 $ffi->type('int[]' => 'var_int_array');
958
959 When used as an argument type it will probe the array reference that
960 you pass in to determine the correct size. Usually you will need to
961 communicate the size of the array to the C code. One way to do this is
962 to pass the length of the array in as an additional argument. For
963 example the C code:
964
965 int
966 sum(int *array, int size)
967 {
968 int total, i;
969 for (i = 0, total = 0; i < size; i++)
970 {
971 total += array[i];
972 }
973 return total;
974 }
975
976 Can be called from Perl like this:
977
978 use FFI::Platypus 1.00;
979
980 my $ffi = FFI::Platypus->new( api => 1 );
981 $ffi->lib('./var_array.so');
982
983 $ffi->attach( sum => [ 'int[]', 'int' ] => 'int' );
984
985 my @list = (1..100);
986
987 print sum(\@list, scalar @list), "\n";
988
989 Another method might be to have a special value, such as 0 or NULL
990 indicate the termination of the array.
991
992 Because of the way records are implemented, an array of records does
993 not make sense and is not currently supported.
994
995 Closures
996 A closure (sometimes called a "callback", we use the "libffi"
997 terminology) is a Perl subroutine that can be called from C. In order
998 to be called from C it needs to be passed to a C function. To define
999 the closure type you need to provide a list of argument types and a
1000 return type. Currently only native types (integers, floating point
1001 values, opaque), strings and records (by-value; you can pass a pointer
1002 to a record, but due to limitations of the record implementation this
1003 is actually a copy) are supported as closure argument types, and only
1004 native types and records (by-value; pointer records and records with
1005 string pointers cannot be returned from a closure) are supported as
1006 closure return types. Inside the closure any records passed in are
1007 read-only.
1008
1009 We plan to add other types, though they can be converted using the
1010 Platypus "cast" or "attach_cast" methods.
1011
1012 Here is an example, with C code:
1013
1014 /*
1015 * closure.c - on Linux compile with: gcc closure.c -shared -o closure.so -fPIC
1016 */
1017
1018 #include <stdio.h>
1019
1020 typedef int (*closure_t)(int);
1021 closure_t my_closure = NULL;
1022
1023 void set_closure(closure_t value)
1024 {
1025 my_closure = value;
1026 }
1027
1028 int call_closure(int value)
1029 {
1030 if(my_closure != NULL)
1031 return my_closure(value);
1032 else
1033 fprintf(stderr, "closure is NULL\n");
1034 }
1035
1036 And the Perl code:
1037
1038 use FFI::Platypus 1.00;
1039
1040 my $ffi = FFI::Platypus->new( api => 1 );
1041 $ffi->lib('./closure.so');
1042 $ffi->type('(int)->int' => 'closure_t');
1043
1044 $ffi->attach(set_closure => ['closure_t'] => 'void');
1045 $ffi->attach(call_closure => ['int'] => 'int');
1046
1047 my $closure1 = $ffi->closure(sub { $_[0] * 2 });
1048 set_closure($closure1);
1049 print call_closure(2), "\n"; # prints "4"
1050
1051 my $closure2 = $ffi->closure(sub { $_[0] * 4 });
1052 set_closure($closure2);
1053 print call_closure(2), "\n"; # prints "8"
1054
1055 If you have a pointer to a function in the form of an "opaque" type,
1056 you can pass this in place of a closure type:
1057
1058 use FFI::Platypus 1.00;
1059
1060 my $ffi = FFI::Platypus->new( api => 1 );
1061 $ffi->lib('./closure.so');
1062 $ffi->type('(int)->int' => 'closure_t');
1063
1064 $ffi->attach(set_closure => ['closure_t'] => 'void');
1065 $ffi->attach(call_closure => ['int'] => 'int');
1066
1067 my $closure = $ffi->closure(sub { $_[0] * 6 });
1068 my $opaque = $ffi->cast(closure_t => 'opaque', $closure);
1069 set_closure($opaque);
1070 print call_closure(2), "\n"; # prints "12"
1071
1072 The syntax for specifying a closure type is a list of comma separated
1073 types in parentheticals followed by a narrow arrow "->", followed by
1074 the return type for the closure. For example a closure that takes a
1075 pointer, an integer and a string and returns an integer would look like
1076 this:
1077
1078 $ffi->type('(opaque, int, string) -> int' => 'my_closure_type');
1079
1080 Care needs to be taken with scoping and closures, because of the way
1081 Perl and C handle responsibility for allocating memory differently.
1082 Perl keeps reference counts and frees objects when nothing is
1083 referencing them. In C the code that allocates the memory is
1084 considered responsible for explicitly free'ing the memory for objects
1085 it has created when they are no longer needed. When you pass a closure
1086 into a C function, the C code has a pointer or reference to that
1087 object, but it has no way up letting Perl know when it is no longer
1088 using it. As a result, if you do not keep a reference to your closure
1089 around it will be free'd by Perl and if the C code ever tries to call
1090 the closure it will probably SIGSEGV. Thus supposing you have a C
1091 function "set_closure" that takes a Perl closure, this is almost always
1092 wrong:
1093
1094 set_closure($ffi->closure({ $_[0] * 2 })); # BAD
1095
1096 In some cases, you may want to create a closure shouldn't ever be
1097 free'd. For example you are passing a closure into a C function that
1098 will retain it for the lifetime of your application. You can use the
1099 sticky method to keep the closure, without the need to keep a reference
1100 of the closure:
1101
1102 {
1103 my $closure = $ffi->closure(sub { $_[0] * 2 });
1104 $closure->sticky;
1105 set_closure($closure); # OKAY
1106 }
1107 # closure still exists and is accesible from C, but
1108 # not from Perl land.
1109
1110 Custom Types
1111 Custom Types in Perl
1112
1113 Platypus custom types are the rough analogue to typemaps in the XS
1114 world. They offer a method for converting Perl types into native types
1115 that the "libffi" can understand and pass on to the C code.
1116
1117 Example 1: Integer constants
1118
1119 Say you have a C header file like this:
1120
1121 /* possible foo types: */
1122 #define FOO_STATIC 1
1123 #define FOO_DYNAMIC 2
1124 #define FOO_OTHER 3
1125
1126 typedef int foo_t;
1127
1128 void foo(foo_t foo);
1129 foo_t get_foo();
1130
1131 The challenge is here that once the source is processed by the C pre-
1132 processor the name/value mappings for these "FOO_" constants are lost.
1133 There is no way to fetch them from the library once it is compiled and
1134 linked.
1135
1136 One common way of implementing this would be to create and export
1137 constants in your Perl module, like this:
1138
1139 package Foo;
1140
1141 use FFI::Platypus 1.00;
1142 use Exporter qw( import );
1143
1144 our @EXPORT_OK = qw( FOO_STATIC FOO_DYNAMIC FOO_OTHER foo get_foo );
1145
1146 use constant FOO_STATIC => 1;
1147 use constant FOO_DYNAMIC => 2;
1148 use constant FOO_OTHER => 3;
1149
1150 my $ffi = FFI::Platypus->new( api => 1 );
1151 $ffi->attach(foo => ['int'] => 'void');
1152 $ffi->attach(get_foo => [] => 'int');
1153
1154 Then you could use the module thus:
1155
1156 use Foo qw( foo FOO_STATIC );
1157 foo(FOO_STATIC);
1158
1159 If you didn't want to rely on integer constants or exports, you could
1160 also define a custom type, and allow strings to be passed into your
1161 function, like this:
1162
1163 package Foo;
1164
1165 use FFI::Platypus 1.00;
1166
1167 our @EXPORT_OK = qw( foo get_foo );
1168
1169 my %foo_types = (
1170 static => 1,
1171 dynamic => 2,
1172 other => 3,
1173 );
1174 my %foo_types_reverse = reverse %foo_types;
1175
1176 my $ffi = FFI::Platypus->new( api => 1 );
1177 $ffi->custom_type(foo_t => {
1178 native_type => 'int',
1179 native_to_perl => sub {
1180 $foo_types{$_[0]};
1181 },
1182 perl_to_native => sub {
1183 $foo_types_reverse{$_[0]};
1184 },
1185 });
1186
1187 $ffi->attach(foo => ['foo_t'] => 'void');
1188 $ffi->attach(get_foo => [] => 'foo_t');
1189
1190 Now when an argument of type "foo_t" is called for it will be converted
1191 from an appropriate string representation, and any function that
1192 returns a "foo_t" type will return a string instead of the integer
1193 representation:
1194
1195 use Foo;
1196 foo('static');
1197
1198 If the library that you are using has a lot of these constants you can
1199 try using Convert::Binary::C or another C header parser to obtain the
1200 appropriate name/value pairings for the constants that you need.
1201
1202 Example 2: Blessed references
1203
1204 Supposing you have a C library that uses an opaque pointer with a
1205 pseudo OO interface, like this:
1206
1207 typedef struct foo_t;
1208
1209 foo_t *foo_new();
1210 void foo_method(foo_t *, int argument);
1211 void foo_free(foo_t *);
1212
1213 One approach to adapting this to Perl would be to create a OO Perl
1214 interface like this:
1215
1216 package Foo;
1217
1218 use FFI::Platypus 1.00;
1219 use FFI::Platypus::API qw( arguments_get_string );
1220
1221 my $ffi = FFI::Platypus->new( api => 1 );
1222 $ffi->custom_type(foo_t => {
1223 native_type => 'opaque',
1224 native_to_perl => sub {
1225 my $class = arguments_get_string(0);
1226 bless \$_[0], $class;
1227 }
1228 perl_to_native => sub { ${$_[0]} },
1229 });
1230
1231 $ffi->attach([ foo_new => 'new' ] => [ 'string' ] => 'foo_t' );
1232 $ffi->attach([ foo_method => 'method' ] => [ 'foo_t', 'int' ] => 'void');
1233 $ffi->attach([ foo_free => 'DESTROY' ] => [ 'foo_t' ] => 'void');
1234
1235 my $foo = Foo->new;
1236
1237 Here we are blessing a reference to the opaque pointer when we return
1238 the custom type for "foo_t", and dereferencing that reference before we
1239 pass it back in. The function "arguments_get_string" queries the C
1240 arguments to get the class name to make sure the object is blessed into
1241 the correct class (for more details on the custom type API see
1242 FFI::Platypus::API), so you can inherit and extend this class like a
1243 normal Perl class. This works because the C "constructor" ignores the
1244 class name that we pass in as the first argument. If you have a C
1245 "constructor" like this that takes arguments you'd have to write a
1246 wrapper for new.
1247
1248 A good example of a C library that uses this pattern, including
1249 inheritance is "libarchive". Platypus comes with a more extensive
1250 example in "examples/archive.pl" that demonstrates this.
1251
1252 Example 3: Pointers with pack / unpack
1253
1254 TODO
1255
1256 See example FFI::Platypus::Type::StringPointer.
1257
1258 Example 4: Custom Type modules and the Custom Type API
1259
1260 TODO
1261
1262 See example FFI::Platypus::Type::PointerSizeBuffer.
1263
1264 Example 5: Custom Type on CPAN
1265
1266 You can distribute your own Platypus custom types on CPAN, if you think
1267 they may be applicable to others. The default namespace is prefix with
1268 "FFI::Platypus::Type::", though you can stick it anywhere (under your
1269 own namespace may make more sense if the custom type is specific to
1270 your application).
1271
1272 A good example and pattern to follow is
1273 FFI::Platypus::Type::StringArray.
1274
1276 FFI::Platypus
1277 Main platypus documentation.
1278
1279 FFI::Platypus::API
1280 Custom types API.
1281
1282 FFI::Platypus::Type::StringPointer
1283 String pointer type.
1284
1286 Author: Graham Ollis <plicease@cpan.org>
1287
1288 Contributors:
1289
1290 Bakkiaraj Murugesan (bakkiaraj)
1291
1292 Dylan Cali (calid)
1293
1294 pipcet
1295
1296 Zaki Mughal (zmughal)
1297
1298 Fitz Elliott (felliott)
1299
1300 Vickenty Fesunov (vyf)
1301
1302 Gregor Herrmann (gregoa)
1303
1304 Shlomi Fish (shlomif)
1305
1306 Damyan Ivanov
1307
1308 Ilya Pavlov (Ilya33)
1309
1310 Petr Písař (ppisar)
1311
1312 Mohammad S Anwar (MANWAR)
1313
1314 Håkon Hægland (hakonhagland, HAKONH)
1315
1316 Meredith (merrilymeredith, MHOWARD)
1317
1318 Diab Jerius (DJERIUS)
1319
1320 Eric Brine (IKEGAMI)
1321
1322 szTheory
1323
1324 José Joaquín Atria (JJATRIA)
1325
1326 Pete Houston (openstrike, HOUSTON)
1327
1329 This software is copyright (c) 2015-2022 by Graham Ollis.
1330
1331 This is free software; you can redistribute it and/or modify it under
1332 the same terms as the Perl 5 programming language system itself.
1333
1334
1335
1336perl v5.34.1 2022-06-20 FFI::Platypus::Type(3)