.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. \*(C+ will
.\" give a nicer C++. Capital omega is used to do unbreakable dashes and
.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
. ds C`
. ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\"
.\" If the F register is >0, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{\
. if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. if !\nF==2 \{\
. nr % 0
. nr F 2
. \}
. \}
.\}
.rr rF
.\" ========================================================================
.\"
.IX Title "FFI::Platypus 3pm"
.TH FFI::Platypus 3pm "2023-01-15" "perl v5.36.0" "User Contributed Perl Documentation"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH "NAME"
FFI::Platypus \- Write Perl bindings to non\-Perl libraries with FFI. No XS required.
.SH "VERSION"
.IX Header "VERSION"
version 2.05
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 1
\& use FFI::Platypus 2.00;
\&
\& # for all new code you should use api => 2
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => undef, # search libc
\& );
\&
\& # call dynamically
\& $ffi\->function( puts => [\*(Aqstring\*(Aq] => \*(Aqint\*(Aq )\->call("hello world");
\&
\& # attach as a xsub and call (much faster)
\& $ffi\->attach( puts => [\*(Aqstring\*(Aq] => \*(Aqint\*(Aq );
\& puts("hello world");
.Ve
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
Platypus is a library for creating interfaces to machine code libraries
written in languages like C, \*(C+,
Go,
Fortran,
Rust,
Pascal. Essentially anything that gets
compiled into machine code. This implementation uses libffi to
accomplish this task. libffi is battle tested by a number of other
scripting and virtual machine languages, such as Python and Ruby to
serve a similar role. There are a number of reasons why you might want
to write an extension with Platypus instead of \s-1XS:\s0
.IP "\s-1FFI /\s0 Platypus does not require messing with the guts of Perl" 4
.IX Item "FFI / Platypus does not require messing with the guts of Perl"
\&\s-1XS\s0 is less of an \s-1API\s0 and more of the guts of perl splayed out to do
whatever you want. That may at times be very powerful, but it can also
be a frustrating exercise in hair pulling.
.IP "\s-1FFI /\s0 Platypus is portable" 4
.IX Item "FFI / Platypus is portable"
Lots of languages have \s-1FFI\s0 interfaces, and it is subjectively easier to
port an extension written in \s-1FFI\s0 in Perl or another language to \s-1FFI\s0 in
another language or Perl. One goal of the Platypus Project is to reduce
common interface specifications to a common format like \s-1JSON\s0 that could
be shared between different languages.
.IP "\s-1FFI /\s0 Platypus could be a bridge to Raku" 4
.IX Item "FFI / Platypus could be a bridge to Raku"
One of those \*(L"other\*(R" languages could be Raku and Raku already has an
\&\s-1FFI\s0 interface I am told.
.IP "\s-1FFI /\s0 Platypus can be reimplemented" 4
.IX Item "FFI / Platypus can be reimplemented"
In a bright future with multiple implementations of Perl 5, each
interpreter will have its own implementation of Platypus, allowing
extensions to be written once and used on multiple platforms, in much
the same way that Ruby-FFI extensions can be use in Ruby, JRuby and
Rubinius.
.IP "\s-1FFI /\s0 Platypus is pure perl (sorta)" 4
.IX Item "FFI / Platypus is pure perl (sorta)"
One Platypus script or module works on any platform where the libraries
it uses are available. That means you can deploy your Platypus script
in a shared filesystem where they may be run on different platforms. It
also means that Platypus modules do not need to be installed in the
platform specific Perl library path.
.IP "\s-1FFI /\s0 Platypus is not C or \*(C+ centric" 4
.IX Item "FFI / Platypus is not C or centric"
\&\s-1XS\s0 is implemented primarily as a bunch of C macros, which requires at
least some understanding of C, the C pre-processor, and some \*(C+ caveats
(since on some platforms Perl is compiled and linked with a \*(C+
compiler). Platypus on the other hand could be used to call other
compiled languages, like Fortran,
Go,
Rust,
Pascal, \*(C+,
or even assembly, allowing you to focus
on your strengths.
.IP "\s-1FFI /\s0 Platypus does not require a parser" 4
.IX Item "FFI / Platypus does not require a parser"
Inline isolates the extension developer from \s-1XS\s0 to some extent, but
it also requires a parser. The various Inline language bindings are
a great technical achievement, but I think writing a parser for every
language that you want to interface with is a bit of an anti-pattern.
.PP
This document consists of an \s-1API\s0 reference, a set of examples, some
support and development (for contributors) information. If you are new
to Platypus or \s-1FFI,\s0 you may want to skip down to the
\&\s-1EXAMPLES\s0 to get a taste of what you can do with Platypus.
.PP
Platypus has extensive documentation of types at FFI::Platypus::Type
and its custom types \s-1API\s0 at FFI::Platypus::API.
.PP
You are \fBstrongly\fR encouraged to use \s-1API\s0 level 1 for all new code.
There are a number of improvements and design fixes that you get
for free. You should even consider updating existing modules to
use \s-1API\s0 level 1 where feasible. How do I do that you might ask?
Simply pass in the \s-1API\s0 level to the platypus constructor.
.PP
.Vb 1
\& my $ffi = FFI::Platypus\->new( api => 2 );
.Ve
.PP
The Platypus documentation has already been updated to assume \s-1API\s0
level 1.
.SH "CONSTRUCTORS"
.IX Header "CONSTRUCTORS"
.SS "new"
.IX Subsection "new"
.Vb 1
\& my $ffi = FFI::Platypus\->new( api => 2, %options);
.Ve
.PP
Create a new instance of FFI::Platypus.
.PP
Any types defined with this instance will be valid for this instance
only, so you do not need to worry about stepping on the toes of other
\&\s-1CPAN FFI /\s0 Platypus Authors.
.PP
Any functions found will be out of the list of libraries specified with
the lib attribute.
.PP
\fIoptions\fR
.IX Subsection "options"
.IP "api" 4
.IX Item "api"
[version 0.91]
.Sp
Sets the \s-1API\s0 level. Legal values are
.RS 4
.ie n .IP "0" 4
.el .IP "\f(CW0\fR" 4
.IX Item "0"
Original \s-1API\s0 level. See FFI::Platypus::TypeParser::Version0 for details
on the differences.
.ie n .IP "1" 4
.el .IP "\f(CW1\fR" 4
.IX Item "1"
Enable version 1 \s-1API\s0 type parser which allows pass-by-value records
and type decoration on basic types.
.ie n .IP "2" 4
.el .IP "\f(CW2\fR" 4
.IX Item "2"
Enable version 2 \s-1API.\s0 All new code should be written with this set to 1!
The Platypus documentation assumes this api level is set.
.Sp
\&\s-1API\s0 version 2 is identical to version 1, except:
.RS 4
.ie n .IP "Pointer functions that return ""NULL"" will return ""undef"" instead of empty list" 4
.el .IP "Pointer functions that return \f(CWNULL\fR will return \f(CWundef\fR instead of empty list" 4
.IX Item "Pointer functions that return NULL will return undef instead of empty list"
This fixes a long standing design bug in Platypus.
.IP "Array references may be passed to pointer argument types" 4
.IX Item "Array references may be passed to pointer argument types"
This replicates the behavior of array argument types with no size. So the types \f(CW\*(C`sint8*\*(C'\fR and \f(CW\*(C`sint8[]\*(C'\fR
behave identically when an array reference is passed in. They differ in that, as before, you can
pass a scalar reference into type \f(CW\*(C`sint8*\*(C'\fR.
.IP "The fixed string type can be specified without pointer modifier" 4
.IX Item "The fixed string type can be specified without pointer modifier"
That is you can use \f(CW\*(C`string(10)\*(C'\fR instead of \f(CW\*(C`string(10)*\*(C'\fR as you were previously able to
in \s-1API 0.\s0
.RE
.RS 4
.RE
.RE
.RS 4
.RE
.IP "lib" 4
.IX Item "lib"
Either a pathname (string) or a list of pathnames (array ref of strings)
to pre-populate the lib attribute. Use \f(CW\*(C`[undef]\*(C'\fR to search the
current process for symbols.
.Sp
0.48
.Sp
\&\f(CW\*(C`undef\*(C'\fR (without the array reference) can be used to search the current
process for symbols.
.IP "ignore_not_found" 4
.IX Item "ignore_not_found"
[version 0.15]
.Sp
Set the ignore_not_found attribute.
.IP "lang" 4
.IX Item "lang"
[version 0.18]
.Sp
Set the lang attribute.
.SH "ATTRIBUTES"
.IX Header "ATTRIBUTES"
.SS "lib"
.IX Subsection "lib"
.Vb 2
\& $ffi\->lib($path1, $path2, ...);
\& my @paths = $ffi\->lib;
.Ve
.PP
The list of libraries to search for symbols in.
.PP
The most portable and reliable way to find dynamic libraries is by using
FFI::CheckLib, like this:
.PP
.Vb 8
\& use FFI::CheckLib 0.06;
\& $ffi\->lib(find_lib_or_die lib => \*(Aqarchive\*(Aq);
\& # finds libarchive.so on Linux
\& # libarchive.bundle on OS X
\& # libarchive.dll (or archive.dll) on Windows
\& # cygarchive\-13.dll on Cygwin
\& # ...
\& # and will die if it isn\*(Aqt found
.Ve
.PP
FFI::CheckLib has a number of options, such as checking for specific
symbols, etc. You should consult the documentation for that module.
.PP
As a special case, if you add \f(CW\*(C`undef\*(C'\fR as a \*(L"library\*(R" to be searched,
Platypus will also search the current process for symbols. This is
mostly useful for finding functions in the standard C library, without
having to know the name of the standard c library for your platform (as
it turns out it is different just about everywhere!).
.PP
You may also use the \*(L"find_lib\*(R" method as a shortcut:
.PP
.Vb 1
\& $ffi\->find_lib( lib => \*(Aqarchive\*(Aq );
.Ve
.SS "ignore_not_found"
.IX Subsection "ignore_not_found"
[version 0.15]
.PP
.Vb 2
\& $ffi\->ignore_not_found(1);
\& my $ignore_not_found = $ffi\->ignore_not_found;
.Ve
.PP
Normally the attach and function methods will
throw an exception if it cannot find the name of the function you
provide it. This will change the behavior such that
function will return \f(CW\*(C`undef\*(C'\fR when the function is not
found and attach will ignore functions that are not found.
This is useful when you are writing bindings to a library and have many
optional functions and you do not wish to wrap every call to
function or attach in an \f(CW\*(C`eval\*(C'\fR.
.SS "lang"
.IX Subsection "lang"
[version 0.18]
.PP
.Vb 1
\& $ffi\->lang($language);
.Ve
.PP
Specifies the foreign language that you will be interfacing with. The
default is C. The foreign language specified with this attribute
changes the default native types (for example, if you specify
Rust, you will get \f(CW\*(C`i32\*(C'\fR as an alias for
\&\f(CW\*(C`sint32\*(C'\fR instead of \f(CW\*(C`int\*(C'\fR as you do with C).
.PP
If the foreign language plugin supports it, this will also enable
Platypus to find symbols using the demangled names (for example, if you
specify \s-1CPP\s0 for \*(C+ you can use method names
like \f(CW\*(C`Foo::get_bar()\*(C'\fR with \*(L"attach\*(R" or \*(L"function\*(R".
.SS "api"
.IX Subsection "api"
[version 1.11]
.PP
.Vb 1
\& my $level = $ffi\->api;
.Ve
.PP
Returns the \s-1API\s0 level of the Platypus instance.
.SH "METHODS"
.IX Header "METHODS"
.SS "type"
.IX Subsection "type"
.Vb 2
\& $ffi\->type($typename);
\& $ffi\->type($typename => $alias);
.Ve
.PP
Define a type. The first argument is the native or C name of the type.
The second argument (optional) is an alias name that you can use to
refer to this new type. See FFI::Platypus::Type for legal type
definitions.
.PP
Examples:
.PP
.Vb 3
\& $ffi\->type(\*(Aqsint32\*(Aq); # only checks to see that sint32 is a valid type
\& $ffi\->type(\*(Aqsint32\*(Aq => \*(Aqmyint\*(Aq); # creates an alias myint for sint32
\& $ffi\->type(\*(Aqbogus\*(Aq); # dies with appropriate diagnostic
.Ve
.SS "custom_type"
.IX Subsection "custom_type"
.Vb 6
\& $ffi\->custom_type($alias => {
\& native_type => $native_type,
\& native_to_perl => $coderef,
\& perl_to_native => $coderef,
\& perl_to_native_post => $coderef,
\& });
.Ve
.PP
Define a custom type. See FFI::Platypus::Type#Custom\-Types for details.
.SS "load_custom_type"
.IX Subsection "load_custom_type"
.Vb 1
\& $ffi\->load_custom_type($name => $alias, @type_args);
.Ve
.PP
Load the custom type defined in the module \fI\f(CI$name\fI\fR, and make an alias
\&\fI\f(CI$alias\fI\fR. If the custom type requires any arguments, they may be passed
in as \fI\f(CI@type_args\fI\fR. See FFI::Platypus::Type#Custom\-Types for
details.
.PP
If \fI\f(CI$name\fI\fR contains \f(CW\*(C`::\*(C'\fR then it will be assumed to be a fully
qualified package name. If not, then \f(CW\*(C`FFI::Platypus::Type::\*(C'\fR will be
prepended to it.
.SS "types"
.IX Subsection "types"
.Vb 2
\& my @types = $ffi\->types;
\& my @types = FFI::Platypus\->types;
.Ve
.PP
Returns the list of types that \s-1FFI\s0 knows about. This will include the
native \f(CW\*(C`libffi\*(C'\fR types (example: \f(CW\*(C`sint32\*(C'\fR, \f(CW\*(C`opaque\*(C'\fR and \f(CW\*(C`double\*(C'\fR) and
the normal C types (example: \f(CW\*(C`unsigned int\*(C'\fR, \f(CW\*(C`uint32_t\*(C'\fR), any types
that you have defined using the type method, and custom types.
.PP
The list of types that Platypus knows about varies somewhat from
platform to platform, FFI::Platypus::Type includes a list of the core
types that you can always count on having access to.
.PP
It can also be called as a class method, in which case, no user defined
or custom types will be included in the list.
.SS "type_meta"
.IX Subsection "type_meta"
.Vb 2
\& my $meta = $ffi\->type_meta($type_name);
\& my $meta = FFI::Platypus\->type_meta($type_name);
.Ve
.PP
Returns a hash reference with the meta information for the given type.
.PP
It can also be called as a class method, in which case, you won't be
able to get meta data on user defined types.
.PP
The format of the meta data is implementation dependent and subject to
change. It may be useful for display or debugging.
.PP
Examples:
.PP
.Vb 4
\& my $meta = $ffi\->type_meta(\*(Aqint\*(Aq); # standard int type
\& my $meta = $ffi\->type_meta(\*(Aqint[64]\*(Aq); # array of 64 ints
\& $ffi\->type(\*(Aqint[128]\*(Aq => \*(Aqmyintarray\*(Aq);
\& my $meta = $ffi\->type_meta(\*(Aqmyintarray\*(Aq); # array of 128 ints
.Ve
.SS "mangler"
.IX Subsection "mangler"
.Vb 1
\& $ffi\->mangler(\e&mangler);
.Ve
.PP
Specify a customer mangler to be used for symbol lookup. This is usually useful
when you are writing bindings for a library where all of the functions have the
same prefix. Example:
.PP
.Vb 4
\& $ffi\->mangler(sub {
\& my($symbol) = @_;
\& return "foo_$symbol";
\& });
\&
\& $ffi\->function( get_bar => [] => \*(Aqint\*(Aq ); # attaches foo_get_bar
\&
\& my $f = $ffi\->function( set_baz => [\*(Aqint\*(Aq] => \*(Aqvoid\*(Aq );
\& $f\->call(22); # calls foo_set_baz
.Ve
.SS "function"
.IX Subsection "function"
.Vb 4
\& my $function = $ffi\->function($name => \e@argument_types => $return_type);
\& my $function = $ffi\->function($address => \e@argument_types => $return_type);
\& my $function = $ffi\->function($name => \e@argument_types => $return_type, \e&wrapper);
\& my $function = $ffi\->function($address => \e@argument_types => $return_type, \e&wrapper);
.Ve
.PP
Returns an object that is similar to a code reference in that it can be
called like one.
.PP
Caveat: many situations require a real code reference, so at the price
of a performance penalty you can get one like this:
.PP
.Vb 2
\& my $function = $ffi\->function(...);
\& my $coderef = sub { $function\->(@_) };
.Ve
.PP
It may be better, and faster to create a real Perl function using the
attach method.
.PP
In addition to looking up a function by name you can provide the address
of the symbol yourself:
.PP
.Vb 2
\& my $address = $ffi\->find_symbol(\*(Aqmy_function\*(Aq);
\& my $function = $ffi\->function($address => ...);
.Ve
.PP
Under the covers, function uses find_symbol
when you provide it with a name, but it is useful to keep this in mind
as there are alternative ways of obtaining a functions address.
Example: a C function could return the address of another C function
that you might want to call.
.PP
[version 0.76]
.PP
If the last argument is a code reference, then it will be used as a
wrapper around the function when called. The first argument to the wrapper
will be the inner function, or if it is later attached an xsub. This can be
used if you need to verify/modify input/output data.
.PP
Examples:
.PP
.Vb 2
\& my $function = $ffi\->function(\*(Aqmy_function_name\*(Aq, [\*(Aqint\*(Aq, \*(Aqstring\*(Aq] => \*(Aqstring\*(Aq);
\& my $return_string = $function\->(1, "hi there");
.Ve
.PP
[version 0.91]
.PP
.Vb 4
\& my $function = $ffi\->function( $name => \e@fixed_argument_types => \e@var_argument_types => $return_type);
\& my $function = $ffi\->function( $name => \e@fixed_argument_types => \e@var_argument_types => $return_type, \e&wrapper);
\& my $function = $ffi\->function( $name => \e@fixed_argument_types => \e@var_argument_types);
\& my $function = $ffi\->function( $name => \e@fixed_argument_types => \e@var_argument_types => \e&wrapper);
.Ve
.PP
Version 0.91 and later allows you to creat functions for c variadic functions
(such as printf, scanf, etc) which can take a variable number of arguments.
The first set of arguments are the fixed set, the second set are the variable
arguments to bind with. The variable argument types must be specified in order
to create a function object, so if you need to call variadic function with
different set of arguments then you will need to create a new function object
each time:
.PP
.Vb 5
\& # int printf(const char *fmt, ...);
\& $ffi\->function( printf => [\*(Aqstring\*(Aq] => [\*(Aqint\*(Aq] => \*(Aqint\*(Aq )
\& \->call("print integer %d\en", 42);
\& $ffi\->function( printf => [\*(Aqstring\*(Aq] => [\*(Aqstring\*(Aq] => \*(Aqint\*(Aq )
\& \->call("print string %s\en", \*(Aqplatypus\*(Aq);
.Ve
.PP
Some older versions of libffi and possibly some platforms may not support
variadic functions. If you try to create a one, then an exception will be
thrown.
.PP
[version 1.26]
.PP
If the return type is omitted then \f(CW\*(C`void\*(C'\fR will be the assumed return type.
.SS "attach"
.IX Subsection "attach"
.Vb 6
\& $ffi\->attach($name => \e@argument_types => $return_type);
\& $ffi\->attach([$c_name => $perl_name] => \e@argument_types => $return_type);
\& $ffi\->attach([$address => $perl_name] => \e@argument_types => $return_type);
\& $ffi\->attach($name => \e@argument_types => $return_type, \e&wrapper);
\& $ffi\->attach([$c_name => $perl_name] => \e@argument_types => $return_type, \e&wrapper);
\& $ffi\->attach([$address => $perl_name] => \e@argument_types => $return_type, \e&wrapper);
.Ve
.PP
Find and attach a C function as a real live Perl xsub. The advantage of
attaching a function over using the function method is that
it is much much much faster since no object resolution needs to be done.
The disadvantage is that it locks the function and the FFI::Platypus
instance into memory permanently, since there is no way to deallocate an
xsub.
.PP
If just one \fI\f(CI$name\fI\fR is given, then the function will be attached in
Perl with the same name as it has in C. The second form allows you to
give the Perl function a different name. You can also provide an
address (the third form), just like with the function
method.
.PP
Examples:
.PP
.Vb 4
\& $ffi\->attach(\*(Aqmy_function_name\*(Aq, [\*(Aqint\*(Aq, \*(Aqstring\*(Aq] => \*(Aqstring\*(Aq);
\& $ffi\->attach([\*(Aqmy_c_function_name\*(Aq => \*(Aqmy_perl_function_name\*(Aq], [\*(Aqint\*(Aq, \*(Aqstring\*(Aq] => \*(Aqstring\*(Aq);
\& my $string1 = my_function_name($int);
\& my $string2 = my_perl_function_name($int);
.Ve
.PP
[version 0.20]
.PP
If the last argument is a code reference, then it will be used as a
wrapper around the attached xsub. The first argument to the wrapper
will be the inner xsub. This can be used if you need to verify/modify
input/output data.
.PP
Examples:
.PP
.Vb 8
\& $ffi\->attach(\*(Aqmy_function\*(Aq, [\*(Aqint\*(Aq, \*(Aqstring\*(Aq] => \*(Aqstring\*(Aq, sub {
\& my($my_function_xsub, $integer, $string) = @_;
\& $integer++;
\& $string .= " and another thing";
\& my $return_string = $my_function_xsub\->($integer, $string);
\& $return_string =~ s/Belgium//; # HHGG remove profanity
\& $return_string;
\& });
.Ve
.PP
[version 0.91]
.PP
.Vb 2
\& $ffi\->attach($name => \e@fixed_argument_types => \e@var_argument_types, $return_type);
\& $ffi\->attach($name => \e@fixed_argument_types => \e@var_argument_types, $return_type, \e&wrapper);
.Ve
.PP
As of version 0.91 you can attach a variadic functions, if it is supported
by the platform / libffi that you are using. For details see the \f(CW\*(C`function\*(C'\fR
documentation. If not supported by the implementation then an exception
will be thrown.
.SS "closure"
.IX Subsection "closure"
.Vb 2
\& my $closure = $ffi\->closure($coderef);
\& my $closure = FFI::Platypus\->closure($coderef);
.Ve
.PP
Prepares a code reference so that it can be used as a \s-1FFI\s0 closure (a
Perl subroutine that can be called from C code). For details on
closures, see FFI::Platypus::Type#Closures and FFI::Platypus::Closure.
.SS "cast"
.IX Subsection "cast"
.Vb 1
\& my $converted_value = $ffi\->cast($original_type, $converted_type, $original_value);
.Ve
.PP
The \f(CW\*(C`cast\*(C'\fR function converts an existing \fI\f(CI$original_value\fI\fR of type
\&\fI\f(CI$original_type\fI\fR into one of type \fI\f(CI$converted_type\fI\fR. Not all types
are supported, so care must be taken. For example, to get the address
of a string, you can do this:
.PP
.Vb 1
\& my $address = $ffi\->cast(\*(Aqstring\*(Aq => \*(Aqopaque\*(Aq, $string_value);
.Ve
.PP
Something that won't work is trying to cast an array to anything:
.PP
.Vb 1
\& my $address = $ffi\->cast(\*(Aqint[10]\*(Aq => \*(Aqopaque\*(Aq, \e@list); # WRONG
.Ve
.SS "attach_cast"
.IX Subsection "attach_cast"
.Vb 3
\& $ffi\->attach_cast("cast_name", $original_type, $converted_type);
\& $ffi\->attach_cast("cast_name", $original_type, $converted_type, \e&wrapper);
\& my $converted_value = cast_name($original_value);
.Ve
.PP
This function attaches a cast as a permanent xsub. This will make it
faster and may be useful if you are calling a particular cast a lot.
.PP
[version 1.26]
.PP
A wrapper may be added as the last argument to \f(CW\*(C`attach_cast\*(C'\fR and works
just like the wrapper for \f(CW\*(C`attach\*(C'\fR and \f(CW\*(C`function\*(C'\fR methods.
.SS "sizeof"
.IX Subsection "sizeof"
.Vb 2
\& my $size = $ffi\->sizeof($type);
\& my $size = FFI::Platypus\->sizeof($type);
.Ve
.PP
Returns the total size of the given type in bytes. For example to get
the size of an integer:
.PP
.Vb 2
\& my $intsize = $ffi\->sizeof(\*(Aqint\*(Aq); # usually 4
\& my $longsize = $ffi\->sizeof(\*(Aqlong\*(Aq); # usually 4 or 8 depending on platform
.Ve
.PP
You can also get the size of arrays
.PP
.Vb 3
\& my $intarraysize = $ffi\->sizeof(\*(Aqint[64]\*(Aq); # usually 4*64
\& my $intarraysize = $ffi\->sizeof(\*(Aqlong[64]\*(Aq); # usually 4*64 or 8*64
\& # depending on platform
.Ve
.PP
Keep in mind that \*(L"pointer\*(R" types will always be the pointer / word size
for the platform that you are using. This includes strings, opaque and
pointers to other types.
.PP
This function is not very fast, so you might want to save this value as
a constant, particularly if you need the size in a loop with many
iterations.
.SS "alignof"
.IX Subsection "alignof"
[version 0.21]
.PP
.Vb 1
\& my $align = $ffi\->alignof($type);
.Ve
.PP
Returns the alignment of the given type in bytes.
.SS "kindof"
.IX Subsection "kindof"
[version 1.24]
.PP
.Vb 1
\& my $kind = $ffi\->kindof($type);
.Ve
.PP
Returns the kind of a type. This is a string with a value of one of
.ie n .IP """void""" 4
.el .IP "\f(CWvoid\fR" 4
.IX Item "void"
.PD 0
.ie n .IP """scalar""" 4
.el .IP "\f(CWscalar\fR" 4
.IX Item "scalar"
.ie n .IP """string""" 4
.el .IP "\f(CWstring\fR" 4
.IX Item "string"
.ie n .IP """closure""" 4
.el .IP "\f(CWclosure\fR" 4
.IX Item "closure"
.ie n .IP """record""" 4
.el .IP "\f(CWrecord\fR" 4
.IX Item "record"
.ie n .IP """record\-value""" 4
.el .IP "\f(CWrecord\-value\fR" 4
.IX Item "record-value"
.ie n .IP """pointer""" 4
.el .IP "\f(CWpointer\fR" 4
.IX Item "pointer"
.ie n .IP """array""" 4
.el .IP "\f(CWarray\fR" 4
.IX Item "array"
.ie n .IP """object""" 4
.el .IP "\f(CWobject\fR" 4
.IX Item "object"
.PD
.SS "countof"
.IX Subsection "countof"
[version 1.24]
.PP
.Vb 1
\& my $count = $ffi\->countof($type);
.Ve
.PP
For array types returns the number of elements in the array (returns 0 for variable length array).
For the \f(CW\*(C`void\*(C'\fR type returns 0. Returns 1 for all other types.
.SS "def"
.IX Subsection "def"
[version 1.24]
.PP
.Vb 2
\& $ffi\->def($package, $type, $value);
\& my $value = $ff\->def($package, $type);
.Ve
.PP
This method allows you to store data for types. If the \f(CW$package\fR is not provided, then the
caller's package will be used. \f(CW$type\fR must be a legal Platypus type for the FFI::Platypus
instance.
.SS "unitof"
.IX Subsection "unitof"
[version 1.24]
.PP
.Vb 1
\& my $unittype = $ffi\->unitof($type);
.Ve
.PP
For array and pointer types, returns the basic type without the array or pointer part.
In other words, for \f(CW\*(C`sin16[]\*(C'\fR or \f(CW\*(C`sint16*\*(C'\fR it will return \f(CW\*(C`sint16\*(C'\fR.
.SS "find_lib"
.IX Subsection "find_lib"
[version 0.20]
.PP
.Vb 1
\& $ffi\->find_lib( lib => $libname );
.Ve
.PP
This is just a shortcut for calling FFI::CheckLib#find_lib and
updating the \*(L"lib\*(R" attribute appropriately. Care should be taken
though, as this method simply passes its arguments to
FFI::CheckLib#find_lib, so if your module or script is depending on a
specific feature in FFI::CheckLib then make sure that you update your
prerequisites appropriately.
.SS "find_symbol"
.IX Subsection "find_symbol"
.Vb 1
\& my $address = $ffi\->find_symbol($name);
.Ve
.PP
Return the address of the given symbol (usually function).
.SS "bundle"
.IX Subsection "bundle"
[version 0.96 api = 1+]
.PP
.Vb 4
\& $ffi\->bundle($package, \e@args);
\& $ffi\->bundle(\e@args);
\& $ffi\->bundle($package);
\& $ffi\->bundle;
.Ve
.PP
This is an interface for bundling compiled code with your
distribution intended to eventually replace the \f(CW\*(C`package\*(C'\fR method documented
above. See FFI::Platypus::Bundle for details on how this works.
.SS "package"
.IX Subsection "package"
[version 0.15 api = 0]
.PP
.Vb 2
\& $ffi\->package($package, $file); # usually _\|_PACKAGE_\|_ and _\|_FILE_\|_ can be used
\& $ffi\->package; # autodetect
.Ve
.PP
\&\fBNote\fR: This method is officially discouraged in favor of \f(CW\*(C`bundle\*(C'\fR
described above.
.PP
If you use FFI::Build (or the older deprecated Module::Build::FFI
to bundle C code with your distribution, you can use this method to tell
the FFI::Platypus instance to look for symbols that came with the
dynamic library that was built when your distribution was installed.
.SS "abis"
.IX Subsection "abis"
.Vb 2
\& my $href = $ffi\->abis;
\& my $href = FFI::Platypus\->abis;
.Ve
.PP
Get the legal ABIs supported by your platform and underlying
implementation. What is supported can vary a lot by \s-1CPU\s0 and by
platform, or even between 32 and 64 bit on the same \s-1CPU\s0 and platform.
They keys are the \*(L"\s-1ABI\*(R"\s0 names, also known as \*(L"calling conventions\*(R". The
values are integers used internally by the implementation to represent
those ABIs.
.SS "abi"
.IX Subsection "abi"
.Vb 1
\& $ffi\->abi($name);
.Ve
.PP
Set the \s-1ABI\s0 or calling convention for use in subsequent calls to
\&\*(L"function\*(R" or \*(L"attach\*(R". May be either a string name or integer
value from the \*(L"abis\*(R" method above.
.SH "EXAMPLES"
.IX Header "EXAMPLES"
Here are some examples. These examples are provided in full with the
Platypus distribution in the \*(L"examples\*(R" directory. There are also some
more examples in FFI::Platypus::Type that are related to types.
.SS "Passing and Returning Integers"
.IX Subsection "Passing and Returning Integers"
\fIC Source\fR
.IX Subsection "C Source"
.PP
.Vb 3
\& int add(int a, int b) {
\& return a+b;
\& }
.Ve
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 3
\& use FFI::Platypus 2.00;
\& use FFI::CheckLib qw( find_lib_or_die );
\& use File::Basename qw( dirname );
\&
\& my $ffi = FFI::Platypus\->new( api => 2, lib => \*(Aq./add.so\*(Aq );
\& $ffi\->attach( add => [\*(Aqint\*(Aq, \*(Aqint\*(Aq] => \*(Aqint\*(Aq );
\&
\& print add(1,2), "\en"; # prints 3
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 3
\& $ cc \-shared \-o add.so add.c
\& $ perl add.pl
\& 3
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
Basic types like integers and floating points are the easiest to pass
across the \s-1FFI\s0 boundary. Because they are values that are passed on
the stack (or through registers) you don't need to worry about memory
allocations or ownership.
.PP
Here we are building our own C dynamic library using the native C
compiler on a Unix like platform. The exact incantation that you
will use to do this would unfortunately depend on your platform and
C compiler.
.PP
By default, Platypus uses the
Platypus C language plugin, which gives you
easy access to many of the basic types used by C APIs. (for example
\&\f(CW\*(C`int\*(C'\fR, \f(CW\*(C`unsigned long\*(C'\fR, \f(CW\*(C`double\*(C'\fR, \f(CW\*(C`size_t\*(C'\fR and others).
.PP
If you are working with another language like
Fortran,
Go,
Rust or
Zig,
you will find similar examples where you can use the Platypus language
plugin for that language and use the native types.
.SS "String Arguments (with puts)"
.IX Subsection "String Arguments (with puts)"
\fIC \s-1API\s0\fR
.IX Subsection "C API"
.PP
cppreference \- puts
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 1
\& use FFI::Platypus 2.00;
\&
\& my $ffi = FFI::Platypus\->new( api => 2, lib => undef );
\& $ffi\->attach( puts => [\*(Aqstring\*(Aq] => \*(Aqint\*(Aq );
\&
\& puts("hello world");
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 2
\& $ perl puts.pl
\& hello world
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
Passing strings into a C function as an argument is also pretty easy
using Platypus. Just use the \f(CW\*(C`string\*(C'\fR type, which is equivalent to
the C or \f(CW\*(C`const char *\*(C'\fR types.
.PP
In this example we are using the C Standard Library's \f(CW\*(C`puts\*(C'\fR function,
so we don't need to build our own C code. We do still need to tell
Platypus where to look for the \f(CW\*(C`puts\*(C'\fR symbol though, which is why
we set \f(CW\*(C`lib\*(C'\fR to \f(CW\*(C`undef\*(C'\fR. This is a special value which tells
Platypus to search the Perl runtime executable itself (including any
dynamic libraries) for symbols. That helpfully includes the C Standard
Library.
.SS "Returning Strings"
.IX Subsection "Returning Strings"
\fIC Source\fR
.IX Subsection "C Source"
.PP
.Vb 2
\& #include
\& #include
\&
\& const char *
\& string_reverse(const char *input)
\& {
\& static char *output = NULL;
\& int i, len;
\&
\& if(output != NULL)
\& free(output);
\&
\& if(input == NULL)
\& return NULL;
\&
\& len = strlen(input);
\& output = malloc(len+1);
\&
\& for(i=0; input[i]; i++)
\& output[len\-i\-1] = input[i];
\& output[len] = \*(Aq\e0\*(Aq;
\&
\& return output;
\& }
.Ve
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 1
\& use FFI::Platypus 2.00;
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => \*(Aq./string_reverse.so\*(Aq,
\& );
\&
\& $ffi\->attach( string_reverse => [\*(Aqstring\*(Aq] => \*(Aqstring\*(Aq );
\&
\& print string_reverse("\enHello world");
\&
\& string_reverse(undef);
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 3
\& $ cc \-shared \-o string_reverse.so string_reverse.c
\& $ perl string_reverse.pl
\& dlrow olleH
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
The C code here takes an input \s-1ASCII\s0 string and reverses it, returning
the result. Note that it retains ownership of the string, the caller
is expected to use it before the next call to \f(CW\*(C`reverse_string\*(C'\fR, or
copy it.
.PP
The Perl code simply declares the return value as \f(CW\*(C`string\*(C'\fR and is very
simple. This does bring up an inconsistency though, strings passed in
to a function as arguments are passed by reference, whereas the return
value is copied! This is usually what you want because C APIs usually
follow this pattern where you are expected to make your own copy of
the string.
.PP
At the end of the program we call \f(CW\*(C`reverse_string\*(C'\fR with \f(CW\*(C`undef\*(C'\fR, which
gets translated to C as \f(CW\*(C`NULL\*(C'\fR. This allows it to free the output buffer
so that the memory will not leak.
.SS "Returning and Freeing Strings with Embedded NULLs"
.IX Subsection "Returning and Freeing Strings with Embedded NULLs"
\fIC Source\fR
.IX Subsection "C Source"
.PP
.Vb 2
\& #include
\& #include
\&
\& char *
\& string_crypt(const char *input, int len, const char *key)
\& {
\& char *output;
\& int i, n;
\&
\& if(input == NULL)
\& return NULL;
\&
\& output = malloc(len+1);
\& output[len] = \*(Aq\e0\*(Aq;
\&
\& for(i=0, n=0; inew(
\& api => 2,
\& lib => \*(Aq./xor_cipher.so\*(Aq,
\& );
\&
\& $ffi\->attach( string_crypt_free => [\*(Aqopaque\*(Aq] );
\&
\& $ffi\->attach( string_crypt => [\*(Aqstring\*(Aq,\*(Aqint\*(Aq,\*(Aqstring\*(Aq] => \*(Aqopaque\*(Aq => sub{
\& my($xsub, $input, $key) = @_;
\& my $ptr = $xsub\->($input, length($input), $key);
\& my $output = buffer_to_scalar $ptr, length($input);
\& string_crypt_free($ptr);
\& return $output;
\& });
\&
\& my $orig = "hello world";
\& my $key = "foobar";
\&
\& print YAML::Dump($orig);
\& my $encrypted = string_crypt($orig, $key);
\& print YAML::Dump($encrypted);
\& my $decrypted = string_crypt($encrypted, $key);
\& print YAML::Dump($decrypted);
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 5
\& $ cc \-shared \-o xor_cipher.so xor_cipher.c
\& $ perl xor_cipher.pl
\& \-\-\- hello world
\& \-\-\- "\ex0e\en\ex03\ex0e\ex0eR\ex11\e0\ex1d\ex0e\ex05"
\& \-\-\- hello world
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
The C code here also returns a string, but it has some different expectations,
so we can't just use the \f(CW\*(C`string\*(C'\fR type like we did in the previous example
and copy the string.
.PP
This C code implements a simple \s-1XOR\s0 cipher. Given an input string and a key
it returns an encrypted or decrypted output string where the characters are
XORd with the key. There are some challenges here though. First the input
and output strings can have embedded \f(CW\*(C`NULL\*(C'\fRs in them. For the string passed
in, we can provide the length of the input string. For the output, the
\&\f(CW\*(C`string\*(C'\fR type expects a \f(CW\*(C`NULL\*(C'\fR terminated string, so we can't use that. So
instead we get a pointer to the output using the \f(CW\*(C`opaque\*(C'\fR type. Because we
know that the output string is the same length as the input string we can
convert the pointer to a regular Perl string using the \f(CW\*(C`buffer_to_scalar\*(C'\fR
function. (For more details about working with buffers and strings see
FFI::Platypus::Buffer).
.PP
Next, the C code here does not keep the pointer to the output string, as in
the previous example. We are expected to call \f(CW\*(C`string_encrypt_free\*(C'\fR when
we are done. Since we are getting the pointer back from the C code instead
of copying the string that is easy to do.
.PP
Finally, we are using a wrapper to hide a lot of this complexity from our
caller. The last argument to the \f(CW\*(C`attach\*(C'\fR call is a code reference which will
wrap around the C function, which is passed in as the first argument of
the wrapper. This is a good practice when writing modules, to hide the
complexity of C.
.SS "Pointers"
.IX Subsection "Pointers"
\fIC Source\fR
.IX Subsection "C Source"
.PP
.Vb 7
\& void
\& swap(int *a, int *b)
\& {
\& int tmp = *b;
\& *b = *a;
\& *a = tmp;
\& }
.Ve
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 1
\& use FFI::Platypus 2.00;
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => \*(Aq./swap.so\*(Aq,
\& );
\&
\& $ffi\->attach( swap => [\*(Aqint*\*(Aq,\*(Aqint*\*(Aq] );
\&
\& my $a = 1;
\& my $b = 2;
\&
\& print "[a,b] = [$a,$b]\en";
\&
\& swap( \e$a, \e$b );
\&
\& print "[a,b] = [$a,$b]\en";
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 4
\& $ cc \-shared \-o swap.so swap.c
\& $ perl swap.pl
\& [a,b] = [1,2]
\& [a,b] = [2,1]
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
Pointers are often use in C APIs to return simple values like this. Platypus
provides access to pointers to primitive types by appending \f(CW\*(C`*\*(C'\fR to the
primitive type. Here for example we are using \f(CW\*(C`int*\*(C'\fR to create a function
that takes two pointers to integers and swaps their values.
.PP
When calling the function from Perl we pass in a reference to a scalar.
Strictly speaking Perl allows modifying the argument values to subroutines, so
we could have allowed just passing in a scalar, but in the design of Platypus
we decided that forcing the use of a reference here emphasizes that you are
passing a reference to the variable, not just the value.
.PP
Not pictured in this example, but you can also pass in \f(CW\*(C`undef\*(C'\fR for a pointer
value and that will be translated into \f(CW\*(C`NULL\*(C'\fR on the C side. You can also
return a pointer to a primitive type from a function, again this will be
returned to Perl as a reference to a scalar. Platypus also supports string
pointers (\f(CW\*(C`string*\*(C'\fR). (Though the C equivalent to a \f(CW\*(C`string*\*(C'\fR is a double
pointer to char \f(CW\*(C`char**\*(C'\fR).
.SS "Opaque Pointers (objects)"
.IX Subsection "Opaque Pointers (objects)"
\fIC Source\fR
.IX Subsection "C Source"
.PP
.Vb 2
\& #include
\& #include
\&
\& typedef struct person_t {
\& char *name;
\& unsigned int age;
\& } person_t;
\&
\& person_t *
\& person_new(const char *name, unsigned int age) {
\& person_t *self = malloc(sizeof(person_t));
\& self\->name = strdup(name);
\& self\->age = age;
\& }
\&
\& const char *
\& person_name(person_t *self) {
\& return self\->name;
\& }
\&
\& unsigned int
\& person_age(person_t *self) {
\& return self\->age;
\& }
\&
\& void
\& person_free(person_t *self) {
\& free(self\->name);
\& free(self);
\& }
.Ve
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 1
\& use FFI::Platypus 2.00;
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => \*(Aq./person.so\*(Aq,
\& );
\&
\& $ffi\->type( \*(Aqopaque\*(Aq => \*(Aqperson_t\*(Aq );
\&
\& $ffi\->attach( person_new => [\*(Aqstring\*(Aq,\*(Aqunsigned int\*(Aq] => \*(Aqperson_t\*(Aq );
\& $ffi\->attach( person_name => [\*(Aqperson_t\*(Aq] => \*(Aqstring\*(Aq );
\& $ffi\->attach( person_age => [\*(Aqperson_t\*(Aq] => \*(Aqunsigned int\*(Aq );
\& $ffi\->attach( person_free => [\*(Aqperson_t\*(Aq] );
\&
\& my $person = person_new( \*(AqRoger Frooble Bits\*(Aq, 35 );
\&
\& print "name = ", person_name($person), "\en";
\& print "age = ", person_age($person), "\en";
\&
\& person_free($person);
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 4
\& $ cc \-shared \-o person.so person.c
\& $ perl person.pl
\& name = Roger Frooble Bits
\& age = 35
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
An opaque pointer is a pointer (memory address) that is pointing to \fIsomething\fR
but you do not know the structure of that something. In C this is usually a
\&\f(CW\*(C`void*\*(C'\fR, but it could also be a pointer to a \f(CW\*(C`struct\*(C'\fR without a defined body.
.PP
This is often used to as an abstraction around objects in C. Here in the C
code we have a \f(CW\*(C`person_t\*(C'\fR struct with functions to create (a constructor), free
(a destructor) and query it (methods).
.PP
The Perl code can then use the constructor, methods and destructors without having
to understand the internals. The \f(CW\*(C`person_t\*(C'\fR internals can also be changed
without having to modify the calling code.
.PP
We use the Platypus type method to create an alias of \f(CW\*(C`opaque\*(C'\fR called
\&\f(CW\*(C`person_t\*(C'\fR. While this is not necessary, it does make the Perl code easier
to understand.
.PP
In later examples we will see how to hide the use of \f(CW\*(C`opaque\*(C'\fR types further
using the \f(CW\*(C`object\*(C'\fR type, but for some code direct use of \f(CW\*(C`opaque\*(C'\fR is
appropriate.
.SS "Opaque Pointers (buffers and strings)"
.IX Subsection "Opaque Pointers (buffers and strings)"
\fIC \s-1API\s0\fR
.IX Subsection "C API"
.IP "cppreference \- free " 4
.IX Item "cppreference - free "
.PD 0
.IP "cppreference \- malloc " 4
.IX Item "cppreference - malloc "
.IP "cppreference \- memcpy " 4
.IX Item "cppreference - memcpy "
.IP "cppreference \- strdup " 4
.IX Item "cppreference - strdup "
.PD
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 2
\& use FFI::Platypus 2.00;
\& use FFI::Platypus::Memory qw( malloc free memcpy strdup );
\&
\& my $ffi = FFI::Platypus\->new( api => 2 );
\& my $buffer = malloc 14;
\& my $ptr_string = strdup("hello there!!\en");
\&
\& memcpy $buffer, $ptr_string, 15;
\&
\& print $ffi\->cast(\*(Aqopaque\*(Aq => \*(Aqstring\*(Aq, $buffer);
\&
\& free $ptr_string;
\& free $buffer;
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 2
\& $ perl malloc.pl
\& hello there!!
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
Another useful application of the \f(CW\*(C`opaque\*(C'\fR type is for dealing with buffers,
and C strings that you do not immediately need to convert into Perl strings.
This example is completely contrived, but we are using \f(CW\*(C`malloc\*(C'\fR to create a
buffer of 14 bytes. We create a C string using \f(CW\*(C`strdup\*(C'\fR, and then copy it
into the buffer using \f(CW\*(C`memcpy\*(C'\fR. When we are done with the \f(CW\*(C`opaque\*(C'\fR pointers
we can free them using \f(CW\*(C`free\*(C'\fR since they. (This is generally only okay when
freeing memory that was allocated by \f(CW\*(C`malloc\*(C'\fR, which is the case for \f(CW\*(C`strdup\*(C'\fR).
.PP
These memory tools, along with others are provided by the FFI::Platypus::Memory
module, which is worth reviewing when you need to manipulate memory from
Perl when writing your \s-1FFI\s0 code.
.PP
Just to verify that the \f(CW\*(C`memcpy\*(C'\fR did the right thing we convert the
buffer into a Perl string and print it out using the Platypus cast method.
.SS "Arrays"
.IX Subsection "Arrays"
\fIC Source\fR
.IX Subsection "C Source"
.PP
.Vb 3
\& void
\& array_reverse(int a[], int len) {
\& int tmp, i;
\&
\& for(i=0; i < len/2; i++) {
\& tmp = a[i];
\& a[i] = a[len\-i\-1];
\& a[len\-i\-1] = tmp;
\& }
\& }
\&
\& void
\& array_reverse10(int a[10]) {
\& array_reverse(a, 10);
\& }
.Ve
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 1
\& use FFI::Platypus 2.00;
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => \*(Aq./array_reverse.so\*(Aq,
\& );
\&
\& $ffi\->attach( array_reverse => [\*(Aqint[]\*(Aq,\*(Aqint\*(Aq] );
\& $ffi\->attach( array_reverse10 => [\*(Aqint[10]\*(Aq] );
\&
\& my @a = (1..10);
\& array_reverse10( \e@a );
\& print "$_ " for @a;
\& print "\en";
\&
\& @a = (1..20);
\& array_reverse( \e@a, 20 );
\& print "$_ " for @a;
\& print "\en";
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 4
\& $ cc \-shared \-o array_reverse.so array_reverse.c
\& $ perl array_reverse.pl
\& 10 9 8 7 6 5 4 3 2 1
\& 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
Arrays in C are passed as pointers, so the C code here reverses the array
in place, rather than returning it. Arrays can also be fixed or variable
length. If the array is variable length the length of the array must be
provided in some way. In this case we explicitly pass in a length. Another
way might be to end the array with \f(CW0\fR, if you don't otherwise expect any
\&\f(CW0\fR to appear in your data. For this reason, Platypus adds a zero (or
\&\f(CW\*(C`NULL\*(C'\fR in the case of pointers) element at the end of the array when passing
it into a variable length array type, although we do not use it here.
.PP
With Platypus you can declare an array type as being either fixed or variable
length. Because Perl stores arrays in completely differently than C, a
temporary array is created by Platypus, passed into the C function as a pointer.
When the function returns the array is re-read by Platypus and the Perl array
is updated with the new values. The temporary array is then freed.
.PP
You can use any primitive type for arrays, even \f(CW\*(C`string\*(C'\fR. You can also
return an array from a function. As in our discussion about strings, when
you return an array the value is copied, which is usually what you want.
.SS "Pointers as Arrays"
.IX Subsection "Pointers as Arrays"
\fIC Source\fR
.IX Subsection "C Source"
.PP
.Vb 1
\& #include
\&
\& int
\& array_sum(const int *a) {
\& int i, sum;
\& if(a == NULL)
\& return \-1;
\& for(i=0, sum=0; a[i] != 0; i++)
\& sum += a[i];
\& return sum;
\& }
.Ve
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 1
\& use FFI::Platypus 2.00;
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => \*(Aq./array_sum.so\*(Aq,
\& );
\&
\& $ffi\->attach( array_sum => [\*(Aqint*\*(Aq] => \*(Aqint\*(Aq );
\&
\& print array_sum(undef), "\en"; # \-1
\& print array_sum([0]), "\en"; # 0
\& print array_sum([1,2,3,0]), "\en"; # 6
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 5
\& $ cc \-shared \-o array_sum.so array_sum.c
\& $ perl array_sum.pl
\& \-1
\& 0
\& 6
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
Starting with the Platypus version 2 \s-1API,\s0 you can also pass an array reference
in to a pointer argument.
.PP
In C pointer and array arguments are often used somewhat interchangeably. In
this example we have an \f(CW\*(C`array_sum\*(C'\fR function that takes a zero terminated
array of integers and computes the sum. If the pointer to the array is zero
(\f(CW0\fR) then we return \f(CW\*(C`\-1\*(C'\fR to indicate an error.
.PP
This is the main advantage from Perl for using pointer argument rather than
an array one: the array argument will not let you pass in \f(CW\*(C`undef\*(C'\fR / \f(CW\*(C`NULL\*(C'\fR.
.SS "Sending Strings to \s-1GUI\s0 on Unix with libnotify"
.IX Subsection "Sending Strings to GUI on Unix with libnotify"
\fIC \s-1API\s0\fR
.IX Subsection "C API"
.PP
Libnotify Reference Manual
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 2
\& use FFI::CheckLib;
\& use FFI::Platypus 2.00;
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => find_lib_or_die(lib => \*(Aqnotify\*(Aq),
\& );
\&
\& $ffi\->attach( notify_init => [\*(Aqstring\*(Aq] );
\& $ffi\->attach( notify_uninit => [] );
\& $ffi\->attach( notify_notification_new => [\*(Aqstring\*(Aq, \*(Aqstring\*(Aq, \*(Aqstring\*(Aq] => \*(Aqopaque\*(Aq );
\& $ffi\->attach( notify_notification_show => [\*(Aqopaque\*(Aq, \*(Aqopaque\*(Aq] );
\&
\& my $message = join "\en",
\& "Hello from Platypus!",
\& "Welcome to the fun",
\& "world of FFI";
\&
\& notify_init(\*(AqPlatypus Hello\*(Aq);
\& my $n = notify_notification_new(\*(AqPlatypus Hello World\*(Aq, $message, \*(Aqdialog\-information\*(Aq);
\& notify_notification_show($n, undef);
\& notify_uninit();
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 1
\& $ perl notify.pl
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
The \s-1GNOME\s0 project provides an \s-1API\s0 to send notifications to its desktop environment.
Nothing here is particularly new: all of the types and techniques are ones that we
have seen before, except we are using a third party library, instead of using our
own C code or the standard C library functions.
.PP
When using a third party library you have to know the name or location of it, which
is not typically portable, so here we use FFI::CheckLib's
find_lib_or_die function. If the library is not
found the script will die with a useful diagnostic. FFI::CheckLib has a number
of useful features and will integrate nicely with Alien::Build based Aliens.
.SS "The Win32 \s-1API\s0 with MessageBoxW"
.IX Subsection "The Win32 API with MessageBoxW"
\fIWin32 \s-1API\s0\fR
.IX Subsection "Win32 API"
.PP
MessageBoxW function (winuser.h)
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 2
\& use utf8;
\& use FFI::Platypus 2.00;
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => [undef],
\& );
\&
\& # see FFI::Platypus::Lang::Win32
\& $ffi\->lang(\*(AqWin32\*(Aq);
\&
\& # Send a Unicode string to the Windows API MessageBoxW function.
\& use constant MB_OK => 0x00000000;
\& use constant MB_DEFAULT_DESKTOP_ONLY => 0x00020000;
\& $ffi\->attach( [MessageBoxW => \*(AqMessageBox\*(Aq] => [ \*(AqHWND\*(Aq, \*(AqLPCWSTR\*(Aq, \*(AqLPCWSTR\*(Aq, \*(AqUINT\*(Aq] => \*(Aqint\*(Aq );
\& MessageBox(undef, "I ❤️ Platypus", "Confession", MB_OK|MB_DEFAULT_DESKTOP_ONLY);
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 1
\& $ perl win32_messagebox.pl
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
The \s-1API\s0 used by Microsoft Windows presents some unique
challenges. On 32 bit systems a different \s-1ABI\s0 is used than what
is used by the standard C library. It also provides a rats nest of
type aliases. Finally if you want to talk Unicode to any of the
Windows \s-1API\s0 you will need to use \f(CW\*(C`UTF\-16LE\*(C'\fR instead of \f(CW\*(C`UTF\-8\*(C'\fR
which is native to Perl. (The Win32 \s-1API\s0 refers to these as
\&\f(CW\*(C`LPWSTR\*(C'\fR and \f(CW\*(C`LPCWSTR\*(C'\fR types). As much as possible the Win32
\&\*(L"language\*(R" plugin attempts to handle these challenges transparently.
For more details see FFI::Platypus::Lang::Win32.
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
The libnotify library is a desktop \s-1GUI\s0 notification system for the
\&\s-1GNOME\s0 Desktop environment. This script sends a notification event that
should show up as a balloon, for me it did so in the upper right hand
corner of my screen.
.SS "Structured Data Records (by pointer or by reference)"
.IX Subsection "Structured Data Records (by pointer or by reference)"
\fIC \s-1API\s0\fR
.IX Subsection "C API"
.PP
cppreference \- localtime
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 2
\& use FFI::Platypus 2.00;
\& use FFI::C;
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => [undef],
\& );
\& FFI::C\->ffi($ffi);
\&
\& package Unix::TimeStruct {
\&
\& FFI::C\->struct(tm => [
\& tm_sec => \*(Aqint\*(Aq,
\& tm_min => \*(Aqint\*(Aq,
\& tm_hour => \*(Aqint\*(Aq,
\& tm_mday => \*(Aqint\*(Aq,
\& tm_mon => \*(Aqint\*(Aq,
\& tm_year => \*(Aqint\*(Aq,
\& tm_wday => \*(Aqint\*(Aq,
\& tm_yday => \*(Aqint\*(Aq,
\& tm_isdst => \*(Aqint\*(Aq,
\& tm_gmtoff => \*(Aqlong\*(Aq,
\& _tm_zone => \*(Aqopaque\*(Aq,
\& ]);
\&
\& # For now \*(Aqstring\*(Aq is unsupported by FFI::C, but we
\& # can cast the time zone from an opaque pointer to
\& # string.
\& sub tm_zone {
\& my $self = shift;
\& $ffi\->cast(\*(Aqopaque\*(Aq, \*(Aqstring\*(Aq, $self\->_tm_zone);
\& }
\&
\& # attach the C localtime function
\& $ffi\->attach( localtime => [\*(Aqtime_t*\*(Aq] => \*(Aqtm\*(Aq, sub {
\& my($inner, $class, $time) = @_;
\& $time = time unless defined $time;
\& $inner\->(\e$time);
\& });
\& }
\&
\& # now we can actually use our Unix::TimeStruct class
\& my $time = Unix::TimeStruct\->localtime;
\& printf "time is %d:%d:%d %s\en",
\& $time\->tm_hour,
\& $time\->tm_min,
\& $time\->tm_sec,
\& $time\->tm_zone;
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 2
\& $ perl time_struct.pl
\& time is 3:48:19 MDT
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
C and other machine code languages frequently provide interfaces that
include structured data records (defined using the \f(CW\*(C`struct\*(C'\fR keyword
in C). Some libraries will provide an \s-1API\s0 which you are expected to read
or write before and/or after passing them along to the library.
.PP
For C pointers to \f(CW\*(C`strict\*(C'\fR, \f(CW\*(C`union\*(C'\fR, nested \f(CW\*(C`struct\*(C'\fR and nested
\&\f(CW\*(C`union\*(C'\fR structures, the easiest interface to use is via \s-1FFI::C\s0.
If you are working with a \f(CW\*(C`struct\*(C'\fR that must be passed by value
(not pointers), then you will want to use FFI::Platypus::Record
class instead. We will discuss an example of that next.
.PP
The C \f(CW\*(C`localtime\*(C'\fR function takes a pointer to a C struct. We simply define
the members of the struct using the \s-1FFI::C\s0 \f(CW\*(C`struct\*(C'\fR method. Because
we used the \f(CW\*(C`ffi\*(C'\fR method to tell \s-1FFI::C\s0 to use our local instance of
FFI::Platypus it registers the \f(CW\*(C`tm\*(C'\fR type for us, and we can just start
using it as a return type!
.SS "Structured Data Records (on stack or by value)"
.IX Subsection "Structured Data Records (on stack or by value)"
\fIC Source\fR
.IX Subsection "C Source"
.PP
.Vb 2
\& #include
\& #include
\&
\& typedef struct color_t {
\& char name[8];
\& uint8_t red;
\& uint8_t green;
\& uint8_t blue;
\& } color_t;
\&
\& color_t
\& color_increase_red(color_t color, uint8_t amount)
\& {
\& strcpy(color.name, "reddish");
\& color.red += amount;
\& return color;
\& }
.Ve
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 1
\& use FFI::Platypus 2.00;
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => \*(Aq./color.so\*(Aq
\& );
\&
\& package Color {
\&
\& use FFI::Platypus::Record;
\& use overload
\& \*(Aq""\*(Aq => sub { shift\->as_string },
\& bool => sub { 1 }, fallback => 1;
\&
\& record_layout_1($ffi,
\& \*(Aqstring(8)\*(Aq => \*(Aqname\*(Aq, qw(
\& uint8 red
\& uint8 green
\& uint8 blue
\& ));
\&
\& sub as_string {
\& my($self) = @_;
\& sprintf "%s: [red:%02x green:%02x blue:%02x]",
\& $self\->name, $self\->red, $self\->green, $self\->blue;
\& }
\&
\& }
\&
\& $ffi\->type(\*(Aqrecord(Color)\*(Aq => \*(Aqcolor_t\*(Aq);
\& $ffi\->attach( color_increase_red => [\*(Aqcolor_t\*(Aq,\*(Aquint8\*(Aq] => \*(Aqcolor_t\*(Aq );
\&
\& my $gray = Color\->new(
\& name => \*(Aqgray\*(Aq,
\& red => 0xDC,
\& green => 0xDC,
\& blue => 0xDC,
\& );
\&
\& my $slightly_red = color_increase_red($gray, 20);
\&
\& print "$gray\en";
\& print "$slightly_red\en";
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 4
\& $ cc \-shared \-o color.so color.c
\& $ perl color.pl
\& gray: [red:dc green:dc blue:dc]
\& reddish: [red:f0 green:dc blue:dc]
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
In the C source of this example, we pass a C \f(CW\*(C`struct\*(C'\fR by value by
copying it onto the stack. On the Perl side we create a \f(CW\*(C`Color\*(C'\fR class
using FFI::Platypus::Record, which allows us to pass the structure
the way the C source wants us to.
.PP
Generally you should only reach for FFI::Platypus::Record if you
need to pass small records on the stack like this. For more complicated
(including nested) data you want to use \s-1FFI::C\s0 using pointers.
.SS "Avoiding Copy Using Memory Windows (with libzmq3)"
.IX Subsection "Avoiding Copy Using Memory Windows (with libzmq3)"
\fIC \s-1API\s0\fR
.IX Subsection "C API"
.PP
ØMQ/3.2.6 \s-1API\s0 Reference
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 8
\& use constant ZMQ_IO_THREADS => 1;
\& use constant ZMQ_MAX_SOCKETS => 2;
\& use constant ZMQ_REQ => 3;
\& use constant ZMQ_REP => 4;
\& use FFI::CheckLib qw( find_lib_or_die );
\& use FFI::Platypus 2.00;
\& use FFI::Platypus::Memory qw( malloc );
\& use FFI::Platypus::Buffer qw( scalar_to_buffer window );
\&
\& my $endpoint = "ipc://zmq\-ffi\-$$";
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => find_lib_or_die lib => \*(Aqzmq\*(Aq,
\& );
\&
\& $ffi\->attach(zmq_version => [\*(Aqint*\*(Aq, \*(Aqint*\*(Aq, \*(Aqint*\*(Aq] => \*(Aqvoid\*(Aq);
\&
\& my($major,$minor,$patch);
\& zmq_version(\e$major, \e$minor, \e$patch);
\& print "libzmq version $major.$minor.$patch\en";
\& die "this script only works with libzmq 3 or better" unless $major >= 3;
\&
\& $ffi\->type(\*(Aqopaque\*(Aq => \*(Aqzmq_context\*(Aq);
\& $ffi\->type(\*(Aqopaque\*(Aq => \*(Aqzmq_socket\*(Aq);
\& $ffi\->type(\*(Aqopaque\*(Aq => \*(Aqzmq_msg_t\*(Aq);
\& $ffi\->attach(zmq_ctx_new => [] => \*(Aqzmq_context\*(Aq);
\& $ffi\->attach(zmq_ctx_set => [\*(Aqzmq_context\*(Aq, \*(Aqint\*(Aq, \*(Aqint\*(Aq] => \*(Aqint\*(Aq);
\& $ffi\->attach(zmq_socket => [\*(Aqzmq_context\*(Aq, \*(Aqint\*(Aq] => \*(Aqzmq_socket\*(Aq);
\& $ffi\->attach(zmq_connect => [\*(Aqopaque\*(Aq, \*(Aqstring\*(Aq] => \*(Aqint\*(Aq);
\& $ffi\->attach(zmq_bind => [\*(Aqzmq_socket\*(Aq, \*(Aqstring\*(Aq] => \*(Aqint\*(Aq);
\& $ffi\->attach(zmq_send => [\*(Aqzmq_socket\*(Aq, \*(Aqopaque\*(Aq, \*(Aqsize_t\*(Aq, \*(Aqint\*(Aq] => \*(Aqint\*(Aq);
\& $ffi\->attach(zmq_msg_init => [\*(Aqzmq_msg_t\*(Aq] => \*(Aqint\*(Aq);
\& $ffi\->attach(zmq_msg_recv => [\*(Aqzmq_msg_t\*(Aq, \*(Aqzmq_socket\*(Aq, \*(Aqint\*(Aq] => \*(Aqint\*(Aq);
\& $ffi\->attach(zmq_msg_data => [\*(Aqzmq_msg_t\*(Aq] => \*(Aqopaque\*(Aq);
\& $ffi\->attach(zmq_errno => [] => \*(Aqint\*(Aq);
\& $ffi\->attach(zmq_strerror => [\*(Aqint\*(Aq] => \*(Aqstring\*(Aq);
\&
\& my $context = zmq_ctx_new();
\& zmq_ctx_set($context, ZMQ_IO_THREADS, 1);
\&
\& my $socket1 = zmq_socket($context, ZMQ_REQ);
\& zmq_connect($socket1, $endpoint);
\&
\& my $socket2 = zmq_socket($context, ZMQ_REP);
\& zmq_bind($socket2, $endpoint);
\&
\& { # send
\& our $sent_message = "hello there";
\& my($pointer, $size) = scalar_to_buffer $sent_message;
\& my $r = zmq_send($socket1, $pointer, $size, 0);
\& die zmq_strerror(zmq_errno()) if $r == \-1;
\& }
\&
\& { # recv
\& my $msg_ptr = malloc 100;
\& zmq_msg_init($msg_ptr);
\& my $size = zmq_msg_recv($msg_ptr, $socket2, 0);
\& die zmq_strerror(zmq_errno()) if $size == \-1;
\& my $data_ptr = zmq_msg_data($msg_ptr);
\& window(my $recv_message, $data_ptr, $size);
\& print "recv_message = $recv_message\en";
\& }
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 3
\& $ perl zmq3.pl
\& libzmq version 4.3.4
\& recv_message = hello there
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
ØMQ is a high-performance asynchronous messaging library. There are a
few things to note here.
.PP
Firstly, sometimes there may be multiple versions of a library in the
wild and you may need to verify that the library on a system meets your
needs (alternatively you could support multiple versions and configure
your bindings dynamically). Here we use \f(CW\*(C`zmq_version\*(C'\fR to ask libzmq
which version it is.
.PP
\&\f(CW\*(C`zmq_version\*(C'\fR returns the version number via three integer pointer
arguments, so we use the pointer to integer type: \f(CW\*(C`int *\*(C'\fR. In order to
pass pointer types, we pass a reference. In this case it is a reference
to an undefined value, because zmq_version will write into the pointers
the output values, but you can also pass in references to integers,
floating point values and opaque pointer types. When the function
returns the \f(CW$major\fR variable (and the others) has been updated and we
can use it to verify that it supports the \s-1API\s0 that we require.
.PP
Finally we attach the necessary functions, send and receive a message.
When we receive we use the FFI::Platypus::Buffer function \f(CW\*(C`window\*(C'\fR
instead of \f(CW\*(C`buffer_to_scalar\*(C'\fR. They have a similar effect in that
the provide a scalar from a region of memory, but \f(CW\*(C`window\*(C'\fR doesn't
have to copy any data, so it is cheaper to call. The only downside
is that a windowed scalar like this is read-only.
.SS "libarchive"
.IX Subsection "libarchive"
\fIC Documentation\fR
.IX Subsection "C Documentation"
.PP
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 2
\& use FFI::Platypus 2.00;
\& use FFI::CheckLib qw( find_lib_or_die );
\&
\& # This example uses FreeBSD\*(Aqs libarchive to list the contents of any
\& # archive format that it suppors. We\*(Aqve also filled out a part of
\& # the ArchiveWrite class that could be used for writing archive formats
\& # supported by libarchive
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => find_lib_or_die(lib => \*(Aqarchive\*(Aq),
\& );
\& $ffi\->type(\*(Aqobject(Archive)\*(Aq => \*(Aqarchive_t\*(Aq);
\& $ffi\->type(\*(Aqobject(ArchiveRead)\*(Aq => \*(Aqarchive_read_t\*(Aq);
\& $ffi\->type(\*(Aqobject(ArchiveWrite)\*(Aq => \*(Aqarchive_write_t\*(Aq);
\& $ffi\->type(\*(Aqobject(ArchiveEntry)\*(Aq => \*(Aqarchive_entry_t\*(Aq);
\&
\& package Archive {
\& # base class is "abstract" having no constructor or destructor
\&
\& $ffi\->mangler(sub {
\& my($name) = @_;
\& "archive_$name";
\& });
\& $ffi\->attach( error_string => [\*(Aqarchive_t\*(Aq] => \*(Aqstring\*(Aq );
\& }
\&
\& package ArchiveRead {
\& our @ISA = qw( Archive );
\&
\& $ffi\->mangler(sub {
\& my($name) = @_;
\& "archive_read_$name";
\& });
\&
\& $ffi\->attach( new => [\*(Aqstring\*(Aq] => \*(Aqarchive_read_t\*(Aq );
\& $ffi\->attach( [ free => \*(AqDESTROY\*(Aq ] => [\*(Aqarchive_t\*(Aq] );
\& $ffi\->attach( support_filter_all => [\*(Aqarchive_t\*(Aq] => \*(Aqint\*(Aq );
\& $ffi\->attach( support_format_all => [\*(Aqarchive_t\*(Aq] => \*(Aqint\*(Aq );
\& $ffi\->attach( open_filename => [\*(Aqarchive_t\*(Aq,\*(Aqstring\*(Aq,\*(Aqsize_t\*(Aq] => \*(Aqint\*(Aq );
\& $ffi\->attach( next_header2 => [\*(Aqarchive_t\*(Aq, \*(Aqarchive_entry_t\*(Aq ] => \*(Aqint\*(Aq );
\& $ffi\->attach( data_skip => [\*(Aqarchive_t\*(Aq] => \*(Aqint\*(Aq );
\& # ... define additional read methods
\& }
\&
\& package ArchiveWrite {
\&
\& our @ISA = qw( Archive );
\&
\& $ffi\->mangler(sub {
\& my($name) = @_;
\& "archive_write_$name";
\& });
\&
\& $ffi\->attach( new => [\*(Aqstring\*(Aq] => \*(Aqarchive_write_t\*(Aq );
\& $ffi\->attach( [ free => \*(AqDESTROY\*(Aq ] => [\*(Aqarchive_write_t\*(Aq] );
\& # ... define additional write methods
\& }
\&
\& package ArchiveEntry {
\&
\& $ffi\->mangler(sub {
\& my($name) = @_;
\& "archive_entry_$name";
\& });
\&
\& $ffi\->attach( new => [\*(Aqstring\*(Aq] => \*(Aqarchive_entry_t\*(Aq );
\& $ffi\->attach( [ free => \*(AqDESTROY\*(Aq ] => [\*(Aqarchive_entry_t\*(Aq] );
\& $ffi\->attach( pathname => [\*(Aqarchive_entry_t\*(Aq] => \*(Aqstring\*(Aq );
\& # ... define additional entry methods
\& }
\&
\& use constant ARCHIVE_OK => 0;
\&
\& # this is a Perl version of the C code here:
\& # https://github.com/libarchive/libarchive/wiki/Examples#List_contents_of_Archive_stored_in_File
\&
\& my $archive_filename = shift @ARGV;
\& unless(defined $archive_filename)
\& {
\& print "usage: $0 archive.tar\en";
\& exit;
\& }
\&
\& my $archive = ArchiveRead\->new;
\& $archive\->support_filter_all;
\& $archive\->support_format_all;
\&
\& my $r = $archive\->open_filename($archive_filename, 1024);
\& die "error opening $archive_filename: ", $archive\->error_string
\& unless $r == ARCHIVE_OK;
\&
\& my $entry = ArchiveEntry\->new;
\&
\& while($archive\->next_header2($entry) == ARCHIVE_OK)
\& {
\& print $entry\->pathname, "\en";
\& $archive\->data_skip;
\& }
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 3
\& $ perl archive_object.pl archive.tar
\& archive.pl
\& archive_object.pl
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
libarchive is the implementation of \f(CW\*(C`tar\*(C'\fR for FreeBSD provided as a
library and available on a number of platforms.
.PP
One interesting thing about libarchive is that it provides a kind of
object oriented interface via opaque pointers. This example creates an
abstract class \f(CW\*(C`Archive\*(C'\fR, and concrete classes \f(CW\*(C`ArchiveWrite\*(C'\fR,
\&\f(CW\*(C`ArchiveRead\*(C'\fR and \f(CW\*(C`ArchiveEntry\*(C'\fR. The concrete classes can even be
inherited from and extended just like any Perl classes because of the
way the custom types are implemented. We use Platypus's \f(CW\*(C`object\*(C'\fR
type for this implementation, which is a wrapper around an \f(CW\*(C`opaque\*(C'\fR
(can also be an integer) type that is blessed into a particular class.
.PP
Another advanced feature of this example is that we define a mangler
to modify the symbol resolution for each class. This means we can do
this when we define a method for Archive:
.PP
.Vb 1
\& $ffi\->attach( support_filter_all => [\*(Aqarchive_t\*(Aq] => \*(Aqint\*(Aq );
.Ve
.PP
Rather than this:
.PP
.Vb 4
\& $ffi\->attach(
\& [ archive_read_support_filter_all => \*(Aqsupport_read_filter_all\*(Aq ] =>
\& [\*(Aqarchive_t\*(Aq] => \*(Aqint\*(Aq );
\& );
.Ve
.PP
As nice as \f(CW\*(C`libarchive\*(C'\fR is, note that we have to shoehorn then
\&\f(CW\*(C`archive_free\*(C'\fR function name into the Perl convention of using
\&\f(CW\*(C`DESTROY\*(C'\fR as the destructor. We can easily do that for just this
one function with:
.PP
.Vb 1
\& $ffi\->attach( [ free => \*(AqDESTROY\*(Aq ] => [\*(Aqarchive_t\*(Aq] );
.Ve
.PP
The \f(CW\*(C`libarchive\*(C'\fR is a large library with hundreds of methods.
For comprehensive \s-1FFI\s0 bindings for \f(CW\*(C`libarchive\*(C'\fR see Archive::Libarchive.
.SS "unix open"
.IX Subsection "unix open"
\fIC \s-1API\s0\fR
.IX Subsection "C API"
.PP
Input-output system calls in C
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 1
\& use FFI::Platypus 2.00;
\&
\& {
\& package FD;
\&
\& use constant O_RDONLY => 0;
\& use constant O_WRONLY => 1;
\& use constant O_RDWR => 2;
\&
\& use constant IN => bless \edo { my $in=0 }, _\|_PACKAGE_\|_;
\& use constant OUT => bless \edo { my $out=1 }, _\|_PACKAGE_\|_;
\& use constant ERR => bless \edo { my $err=2 }, _\|_PACKAGE_\|_;
\&
\& my $ffi = FFI::Platypus\->new( api => 2, lib => [undef]);
\&
\& $ffi\->type(\*(Aqobject(FD,int)\*(Aq => \*(Aqfd\*(Aq);
\&
\& $ffi\->attach( [ \*(Aqopen\*(Aq => \*(Aqnew\*(Aq ] => [ \*(Aqstring\*(Aq, \*(Aqint\*(Aq, \*(Aqmode_t\*(Aq ] => \*(Aqfd\*(Aq => sub {
\& my($xsub, $class, $fn, @rest) = @_;
\& my $fd = $xsub\->($fn, @rest);
\& die "error opening $fn $!" if $$fd == \-1;
\& $fd;
\& });
\&
\& $ffi\->attach( write => [\*(Aqfd\*(Aq, \*(Aqstring\*(Aq, \*(Aqsize_t\*(Aq ] => \*(Aqssize_t\*(Aq );
\& $ffi\->attach( read => [\*(Aqfd\*(Aq, \*(Aqstring\*(Aq, \*(Aqsize_t\*(Aq ] => \*(Aqssize_t\*(Aq );
\& $ffi\->attach( close => [\*(Aqfd\*(Aq] => \*(Aqint\*(Aq );
\& }
\&
\& my $fd = FD\->new("file_handle.txt", FD::O_RDONLY);
\&
\& my $buffer = "\e0" x 10;
\&
\& while(my $br = $fd\->read($buffer, 10))
\& {
\& FD::OUT\->write($buffer, $br);
\& }
\&
\& $fd\->close;
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 2
\& $ perl file_handle.pl
\& Hello World
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
The Unix file system calls use an integer handle for each open file.
We can use the same \f(CW\*(C`object\*(C'\fR type that we used for libarchive above,
except we let platypus know that the underlying type is \f(CW\*(C`int\*(C'\fR instead
of \f(CW\*(C`opaque\*(C'\fR (the latter being the default for the \f(CW\*(C`object\*(C'\fR type).
Mainly just for demonstration since Perl has much better \s-1IO\s0 libraries,
but now we have an \s-1OO\s0 interface to the Unix \s-1IO\s0 functions.
.SS "Varadic Functions (with libcurl)"
.IX Subsection "Varadic Functions (with libcurl)"
\fIC \s-1API\s0\fR
.IX Subsection "C API"
.IP "curl_easy_init " 4
.IX Item "curl_easy_init "
.PD 0
.IP "curl_easy_setopt " 4
.IX Item "curl_easy_setopt "
.IP "curl_easy_perform " 4
.IX Item "curl_easy_perform "
.IP "curl_easy_cleanup " 4
.IX Item "curl_easy_cleanup "
.IP "\s-1CURLOPT_URL\s0 " 4
.IX Item "CURLOPT_URL "
.PD
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 3
\& use FFI::Platypus 2.00;
\& use FFI::CheckLib qw( find_lib_or_die );
\& use constant CURLOPT_URL => 10002;
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => find_lib_or_die(lib => \*(Aqcurl\*(Aq),
\& );
\&
\& my $curl_handle = $ffi\->function( \*(Aqcurl_easy_init\*(Aq => [] => \*(Aqopaque\*(Aq )
\& \->call;
\&
\& $ffi\->function( \*(Aqcurl_easy_setopt\*(Aq => [\*(Aqopaque\*(Aq, \*(Aqenum\*(Aq ] => [\*(Aqstring\*(Aq] )
\& \->call($curl_handle, CURLOPT_URL, "https://pl.atypus.org" );
\&
\& $ffi\->function( \*(Aqcurl_easy_perform\*(Aq => [\*(Aqopaque\*(Aq ] => \*(Aqenum\*(Aq )
\& \->call($curl_handle);
\&
\& $ffi\->function( \*(Aqcurl_easy_cleanup\*(Aq => [\*(Aqopaque\*(Aq ] )
\& \->call($curl_handle);
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 7
\& $ perl curl.pl
\&
\&
\&
\&
\& pl.atypus.org \- Home for the Perl Platypus Project
\& ...
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
The libcurl library makes extensive use of \*(L"varadic\*(R" functions.
.PP
The C programming language and \s-1ABI\s0 have the concept of \*(L"varadic\*(R" functions
that can take a variable number and variable type of arguments. Assuming
you have a \f(CW\*(C`libffi\*(C'\fR that supports it (and most modern systems should),
then you can create bindings to a varadic function by providing two sets
of array references, one for the fixed arguments (for reasons, C varadic
functions must have at least one) and one for variable arguments. In
this example we call \f(CW\*(C`curl_easy_setopt\*(C'\fR as a varadic function.
.PP
For functions that have a large or infinite number of possible signatures
it may be impracticable or impossible to attach them all. You can instead
do as we did in this example, create a function object using the
function method and call it immediately. This is not as
performant either when you create or call as using the attach method,
but in some cases the performance penalty may be worth it or unavoidable.
.SS "Callbacks (with libcurl)"
.IX Subsection "Callbacks (with libcurl)"
\fIC \s-1API\s0\fR
.IX Subsection "C API"
.IP "curl_easy_init " 4
.IX Item "curl_easy_init "
.PD 0
.IP "curl_easy_setopt " 4
.IX Item "curl_easy_setopt "
.IP "curl_easy_perform " 4
.IX Item "curl_easy_perform "
.IP "curl_easy_cleanup " 4
.IX Item "curl_easy_cleanup "
.IP "\s-1CURLOPT_URL\s0 " 4
.IX Item "CURLOPT_URL "
.IP "\s-1CURLOPT_WRITEFUNCTION\s0 " 4
.IX Item "CURLOPT_WRITEFUNCTION "
.PD
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
.Vb 5
\& use FFI::Platypus 2.00;
\& use FFI::CheckLib qw( find_lib_or_die );
\& use FFI::Platypus::Buffer qw( window );
\& use constant CURLOPT_URL => 10002;
\& use constant CURLOPT_WRITEFUNCTION => 20011;
\&
\& my $ffi = FFI::Platypus\->new(
\& api => 2,
\& lib => find_lib_or_die(lib => \*(Aqcurl\*(Aq),
\& );
\&
\& my $curl_handle = $ffi\->function( \*(Aqcurl_easy_init\*(Aq => [] => \*(Aqopaque\*(Aq )
\& \->call;
\&
\& $ffi\->function( \*(Aqcurl_easy_setopt\*(Aq => [ \*(Aqopaque\*(Aq, \*(Aqenum\*(Aq ] => [\*(Aqstring\*(Aq] )
\& \->call($curl_handle, CURLOPT_URL, "https://pl.atypus.org" );
\&
\& my $html;
\&
\& my $closure = $ffi\->closure(sub {
\& my($ptr, $len, $num, $user) = @_;
\& window(my $buf, $ptr, $len*$num);
\& $html .= $buf;
\& return $len*$num;
\& });
\&
\& $ffi\->function( \*(Aqcurl_easy_setopt\*(Aq => [ \*(Aqopaque\*(Aq, \*(Aqenum\*(Aq ] => [\*(Aq(opaque,size_t,size_t,opaque)\->size_t\*(Aq] => \*(Aqenum\*(Aq )
\& \->call($curl_handle, CURLOPT_WRITEFUNCTION, $closure);
\&
\& $ffi\->function( \*(Aqcurl_easy_perform\*(Aq => [ \*(Aqopaque\*(Aq ] => \*(Aqenum\*(Aq )
\& \->call($curl_handle);
\&
\& $ffi\->function( \*(Aqcurl_easy_cleanup\*(Aq => [ \*(Aqopaque\*(Aq ] )
\& \->call($curl_handle);
\&
\& if($html =~ /(.*?)<\e/title>/) {
\& print "$1\en";
\& }
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
.Vb 2
\& $ perl curl_callback.pl
\& pl.atypus.org \- Home for the Perl Platypus Project
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
This example is similar to the previous one, except instead of letting
libcurl write the content body to \f(CW\*(C`STDOUT\*(C'\fR, we give
it a callback to send the data to instead. The closure method
can be used to create a callback function pointer that can be called from
C. The type for the callback is in the form \f(CW\*(C`(arg_type,arg_type,etc)\->return_type\*(C'\fR
where the argument types are in parentheticals with an arrow between the
argument types and the return type.
.PP
Inside the closure or callback we use the window function
from FFI::Platypus::Buffer again to avoid an \fIextra\fR copy. We still
have to copy the buffer to append it to \f(CW$hmtl\fR but it is at least one
less copy.
.SS "bundle your own code"
.IX Subsection "bundle your own code"
\fIC Source\fR
.IX Subsection "C Source"
.PP
\&\f(CW\*(C`ffi/foo.c\*(C'\fR:
.PP
.Vb 2
\& #include
\& #include
\&
\& typedef struct {
\& char *name;
\& int value;
\& } foo_t;
\&
\& foo_t*
\& foo_\|_new(const char *class_name, const char *name, int value) {
\& (void)class_name;
\& foo_t *self = malloc( sizeof( foo_t ) );
\& self\->name = strdup(name);
\& self\->value = value;
\& return self;
\& }
\&
\& const char *
\& foo_\|_name(foo_t *self) {
\& return self\->name;
\& }
\&
\& int
\& foo_\|_value(foo_t *self) {
\& return self\->value;
\& }
\&
\& void
\& foo_\|_DESTROY(foo_t *self) {
\& free(self\->name);
\& free(self);
\& }
.Ve
.PP
\fIPerl Source\fR
.IX Subsection "Perl Source"
.PP
\&\f(CW\*(C`lib/Foo.pm\*(C'\fR:
.PP
.Vb 1
\& package Foo;
\&
\& use strict;
\& use warnings;
\& use FFI::Platypus 2.00;
\&
\& my $ffi = FFI::Platypus\->new( api => 2 );
\&
\& $ffi\->type(\*(Aqobject(Foo)\*(Aq => \*(Aqfoo_t\*(Aq);
\& $ffi\->mangler(sub {
\& my $name = shift;
\& $name =~ s/^/foo_\|_/;
\& $name;
\& });
\&
\& $ffi\->bundle;
\&
\& $ffi\->attach( new => [ \*(Aqstring\*(Aq, \*(Aqstring\*(Aq, \*(Aqint\*(Aq ] => \*(Aqfoo_t\*(Aq );
\& $ffi\->attach( name => [ \*(Aqfoo_t\*(Aq ] => \*(Aqstring\*(Aq );
\& $ffi\->attach( value => [ \*(Aqfoo_t\*(Aq ] => \*(Aqint\*(Aq );
\& $ffi\->attach( DESTROY => [ \*(Aqfoo_t\*(Aq ] => \*(Aqvoid\*(Aq );
\&
\& 1;
.Ve
.PP
\&\f(CW\*(C`t/foo.t\*(C'\fR:
.PP
.Vb 2
\& use Test2::V0;
\& use Foo;
\&
\& my $foo = Foo\->new("platypus", 10);
\& isa_ok $foo, \*(AqFoo\*(Aq;
\& is $foo\->name, "platypus";
\& is $foo\->value, 10;
\&
\& done_testing;
.Ve
.PP
\&\f(CW\*(C`Makefile.PL\*(C'\fR:
.PP
.Vb 11
\& use ExtUtils::MakeMaker;
\& use FFI::Build::MM;
\& my $fbmm = FFI::Build::MM\->new;
\& WriteMakefile(
\& $fbmm\->mm_args(
\& NAME => \*(AqFoo\*(Aq,
\& DISTNAME => \*(AqFoo\*(Aq,
\& VERSION => \*(Aq1.00\*(Aq,
\& # ...
\& )
\& );
\&
\& sub MY::postamble
\& {
\& $fbmm\->mm_postamble;
\& }
.Ve
.PP
\fIExecute\fR
.IX Subsection "Execute"
.PP
With prove:
.PP
.Vb 11
\& $ prove \-lvm
\& t/foo.t ..
\& # Seeded srand with seed \*(Aq20221105\*(Aq from local date.
\& ok 1 \- Foo=SCALAR\->isa(\*(AqFoo\*(Aq)
\& ok 2
\& ok 3
\& 1..3
\& ok
\& All tests successful.
\& Files=1, Tests=3, 0 wallclock secs ( 0.00 usr 0.00 sys + 0.10 cusr 0.00 csys = 0.10 CPU)
\& Result: PASS
.Ve
.PP
With ExtUtils::MakeMaker:
.PP
.Vb 10
\& $ perl Makefile.PL
\& Generating a Unix\-style Makefile
\& Writing Makefile for Foo
\& Writing MYMETA.yml and MYMETA.json
\& $ make
\& cp lib/Foo.pm blib/lib/Foo.pm
\& "/home/ollisg/opt/perl/5.37.5/bin/perl5.37.5" \-MFFI::Build::MM=cmd \-e fbx_build
\& CC ffi/foo.c
\& LD blib/lib/auto/share/dist/Foo/lib/libFoo.so
\& $ make test
\& "/home/ollisg/opt/perl/5.37.5/bin/perl5.37.5" \-MFFI::Build::MM=cmd \-e fbx_build
\& "/home/ollisg/opt/perl/5.37.5/bin/perl5.37.5" \-MFFI::Build::MM=cmd \-e fbx_test
\& PERL_DL_NONLAZY=1 "/home/ollisg/opt/perl/5.37.5/bin/perl5.37.5" "\-MExtUtils::Command::MM" "\-MTest::Harness" "\-e" "undef *Test::Harness::Switches; test_harness(0, \*(Aqblib/lib\*(Aq, \*(Aqblib/arch\*(Aq)" t/*.t
\& t/foo.t .. ok
\& All tests successful.
\& Files=1, Tests=3, 1 wallclock secs ( 0.00 usr 0.00 sys + 0.03 cusr 0.00 csys = 0.03 CPU)
\& Result: PASS
.Ve
.PP
\fIDiscussion\fR
.IX Subsection "Discussion"
.PP
You can bundle your own C code with your Perl extension. There are a number
of reasons you might want to do this Sometimes you need to optimize a
tight loop for speed. Or you might need a little bit of glue code for your
bindings to a library that isn't inherently \s-1FFI\s0 friendly. Either way
what you want is the FFI::Build system on the install step and the
FFI::Platypus::Bundle interface on the runtime step. If you are using
Dist::Zilla for your distribution, you will also want to check out the
Dist::Zilla::Plugin::FFI::Build plugin to make this as painless as possible.
.PP
One of the nice things about the bundle interface is that it is smart enough to
work with either App::Prove or ExtUtils::MakeMaker. This means, unlike
\&\s-1XS,\s0 you do not need to explicitly compile your C code in development mode, that
will be done for you when you call \f(CW\*(C`$ffi\->bundle\*(C'\fR
.SH "FAQ"
.IX Header "FAQ"
.SS "How do I get constants defined as macros in C header files"
.IX Subsection "How do I get constants defined as macros in C header files"
This turns out to be a challenge for any language calling into C, which
frequently uses \f(CW\*(C`#define\*(C'\fR macros to define constants like so:
.PP
.Vb 3
\& #define FOO_STATIC 1
\& #define FOO_DYNAMIC 2
\& #define FOO_OTHER 3
.Ve
.PP
As macros are expanded and their definitions are thrown away by the C pre-processor
there isn't any way to get the name/value mappings from the compiled dynamic
library.
.PP
You can manually create equivalent constants in your Perl source:
.PP
.Vb 3
\& use constant FOO_STATIC => 1;
\& use constant FOO_DYNAMIC => 2;
\& use constant FOO_OTHER => 3;
.Ve
.PP
If there are a lot of these types of constants you might want to consider using
a tool (Convert::Binary::C can do this) that can extract the constants for you.
.PP
See also the \*(L"Integer constants\*(R" example in FFI::Platypus::Type.
.PP
You can also use the new Platypus bundle interface to define Perl constants
from C space. This is more reliable, but does require a compiler at install
time. It is recommended mainly for writing bindings against libraries that
have constants that can vary widely from platform to platform. See
FFI::Platypus::Constant for details.
.SS "What about enums?"
.IX Subsection "What about enums?"
The C enum types are integers. The underlying type is up to the platform, so
Platypus provides \f(CW\*(C`enum\*(C'\fR and \f(CW\*(C`senum\*(C'\fR types for unsigned and singed enums
respectively. At least some compilers treat signed and unsigned enums as
different types. The enum \fIvalues\fR are essentially the same as macro constants
described above from an \s-1FFI\s0 perspective. Thus the process of defining enum values
is identical to the process of defining macro constants in Perl.
.PP
For more details on enumerated types see \*(L"Enum types\*(R" in FFI::Platypus::Type.
.PP
There is also a type plugin (FFI::Platypus::Type::Enum) that can be helpful
in writing interfaces that use enums.
.SS "Memory leaks"
.IX Subsection "Memory leaks"
There are a couple places where memory is allocated, but never deallocated that may
look like memory leaks by tools designed to find memory leaks like valgrind. This
memory is intended to be used for the lifetime of the perl process so there normally
this isn't a problem unless you are embedding a Perl interpreter which doesn't closely
match the lifetime of your overall application.
.PP
Specifically:
.IP "type cache" 4
.IX Item "type cache"
some types are cached and not freed. These are needed as long as there are \s-1FFI\s0
functions that could be called.
.IP "attached functions" 4
.IX Item "attached functions"
Attaching a function as an xsub will definitely allocate memory that won't be freed
because the xsub could be called at any time, including in \f(CW\*(C`END\*(C'\fR blocks.
.PP
The Platypus team plans on adding a hook to free some of this \*(L"leaked\*(R" memory
for use cases where Perl and Platypus are embedded in a larger application
where the lifetime of the Perl process is significantly smaller than the
overall lifetime of the whole process.
.SS "I get seg faults on some platforms but not others with a library using pthreads."
.IX Subsection "I get seg faults on some platforms but not others with a library using pthreads."
On some platforms, Perl isn't linked with \f(CW\*(C`libpthreads\*(C'\fR if Perl threads are not
enabled. On some platforms this doesn't seem to matter, \f(CW\*(C`libpthreads\*(C'\fR can be
loaded at runtime without much ill-effect. (Linux from my experience doesn't seem
to mind one way or the other). Some platforms are not happy about this, and about
the only thing that you can do about it is to build Perl such that it links with
\&\f(CW\*(C`libpthreads\*(C'\fR even if it isn't a threaded Perl.
.PP
This is not really an \s-1FFI\s0 issue, but a Perl issue, as you will have the same
problem writing \s-1XS\s0 code for the such libraries.
.SS "Doesn't work on Perl 5.10.0."
.IX Subsection "Doesn't work on Perl 5.10.0."
The first point release of Perl 5.10 was buggy, and is not supported by Platypus.
Please upgrade to a newer Perl.
.SH "CAVEATS"
.IX Header "CAVEATS"
Platypus and Native Interfaces like libffi rely on the availability of
dynamic libraries. Things not supported include:
.IP "Systems that lack dynamic library support" 4
.IX Item "Systems that lack dynamic library support"
Like MS-DOS
.IP "Systems that are not supported by libffi" 4
.IX Item "Systems that are not supported by libffi"
Like OpenVMS
.IP "Languages that do not support using dynamic libraries from other languages" 4
.IX Item "Languages that do not support using dynamic libraries from other languages"
This used to be the case with Google's Go, but is no longer the case. This is
a problem for C / \s-1XS\s0 code as well.
.IP "Languages that do not compile to machine code" 4
.IX Item "Languages that do not compile to machine code"
Like .NET based languages and Java.
.PP
The documentation has a bias toward using \s-1FFI /\s0 Platypus with C. This
is my fault, as my background in mainly in C/\*(C+ programmer (when I am
not writing Perl). In many places I use \*(L"C\*(R" as a short form for \*(L"any
language that can generate machine code and is callable from C\*(R". I
welcome pull requests to the Platypus core to address this issue. In an
attempt to ease usage of Platypus by non C programmers, I have written a
number of foreign language plugins for various popular languages (see
the \s-1SEE ALSO\s0 below). These plugins come with examples specific to those
languages, and documentation on common issues related to using those
languages with \s-1FFI.\s0 In most cases these are available for easy adoption
for those with the know-how or the willingness to learn. If your
language doesn't have a plugin \s-1YET,\s0 that is just because you haven't
written it yet.
.SH "SUPPORT"
.IX Header "SUPPORT"
\&\s-1IRC:\s0 #native on irc.perl.org
.PP
(click for instant chat room login)
.PP
If something does not work the way you think it should, or if you have a
feature request, please open an issue on this project's GitHub Issue
tracker:
.PP
.SH "CONTRIBUTING"
.IX Header "CONTRIBUTING"
If you have implemented a new feature or fixed a bug then you may make a
pull request on this project's GitHub repository:
.PP
.PP
This project is developed using Dist::Zilla. The project's git
repository also comes with the \f(CW\*(C`Makefile.PL\*(C'\fR file necessary
for building, testing (and even installing if necessary) without
Dist::Zilla. Please keep in mind though that these files are
generated so if changes need to be made to those files they should be
done through the project's \f(CW\*(C`dist.ini\*(C'\fR file. If you do use
Dist::Zilla and already have the necessary plugins installed, then I
encourage you to run \f(CW\*(C`dzil test\*(C'\fR before making any pull requests. This
is not a requirement, however, I am happy to integrate especially
smaller patches that need tweaking to fit the project standards. I may
push back and ask you to write a test case or alter the formatting of a
patch depending on the amount of time I have and the amount of code that
your patch touches.
.PP
This project's GitHub issue tracker listed above is not Write-Only. If
you want to contribute then feel free to browse through the existing
issues and see if there is something you feel you might be good at and
take a whack at the problem. I frequently open issues myself that I
hope will be accomplished by someone in the future but do not have time
to immediately implement myself.
.PP
Another good area to help out in is documentation. I try to make sure
that there is good document coverage, that is there should be
documentation describing all the public features and warnings about
common pitfalls, but an outsider's or alternate view point on such
things would be welcome; if you see something confusing or lacks
sufficient detail I encourage documentation only pull requests to
improve things.
.PP
The Platypus distribution comes with a test library named \f(CW\*(C`libtest\*(C'\fR
that is normally automatically built by \f(CW\*(C`./Build test\*(C'\fR. If you prefer
to use \f(CW\*(C`prove\*(C'\fR or run tests directly, you can use the \f(CW\*(C`./Build
libtest\*(C'\fR command to build it. Example:
.PP
.Vb 6
\& % perl Makefile.PL
\& % make
\& % make ffi\-test
\& % prove \-bv t
\& # or an individual test
\& % perl \-Mblib t/ffi_platypus_memory.t
.Ve
.PP
The build process also respects these environment variables:
.IP "\s-1FFI_PLATYPUS_DEBUG_FAKE32\s0" 4
.IX Item "FFI_PLATYPUS_DEBUG_FAKE32"
When building Platypus on 32 bit Perls, it will use the Math::Int64 C
\&\s-1API\s0 and make Math::Int64 a prerequisite. Setting this environment
variable will force Platypus to build with both of those options on a 64
bit Perl as well.
.Sp
.Vb 8
\& % env FFI_PLATYPUS_DEBUG_FAKE32=1 perl Makefile.PL
\& DEBUG_FAKE32:
\& + making Math::Int64 a prereq
\& + Using Math::Int64\*(Aqs C API to manipulate 64 bit values
\& Generating a Unix\-style Makefile
\& Writing Makefile for FFI::Platypus
\& Writing MYMETA.yml and MYMETA.json
\& %
.Ve
.IP "\s-1FFI_PLATYPUS_NO_ALLOCA\s0" 4
.IX Item "FFI_PLATYPUS_NO_ALLOCA"
Platypus uses the non-standard and somewhat controversial C function
\&\f(CW\*(C`alloca\*(C'\fR by default on platforms that support it. I believe that
Platypus uses it responsibly to allocate small amounts of memory for
argument type parameters, and does not use it to allocate large
structures like arrays or buffers. If you prefer not to use \f(CW\*(C`alloca\*(C'\fR
despite these precautions, then you can turn its use off by setting this
environment variable when you run \f(CW\*(C`Makefile.PL\*(C'\fR:
.Sp
.Vb 6
\& helix% env FFI_PLATYPUS_NO_ALLOCA=1 perl Makefile.PL
\& NO_ALLOCA:
\& + alloca() will not be used, even if your platform supports it.
\& Generating a Unix\-style Makefile
\& Writing Makefile for FFI::Platypus
\& Writing MYMETA.yml and MYMETA.json
.Ve
.IP "V" 4
.IX Item "V"
When building platypus may hide some of the excessive output when
probing and building, unless you set \f(CW\*(C`V\*(C'\fR to a true value.
.Sp
.Vb 3
\& % env V=1 perl Makefile.PL
\& % make V=1
\& ...
.Ve
.SS "Coding Guidelines"
.IX Subsection "Coding Guidelines"
.IP "\(bu" 4
Do not hesitate to make code contribution. Making useful contributions
is more important than following byzantine bureaucratic coding
regulations. We can always tweak things later.
.IP "\(bu" 4
Please make an effort to follow existing coding style when making pull
requests.
.IP "\(bu" 4
Platypus supports all production Perl releases since 5.8.1. For that
reason, please do not introduce any code that requires a newer version
of Perl.
.SS "Performance Testing"
.IX Subsection "Performance Testing"
As Mark Twain was fond of saying there are four types of lies: lies,
damn lies, statistics and benchmarks. That being said, it can sometimes
be helpful to compare the runtime performance of Platypus if you are
making significant changes to the Platypus Core. For that I use
`FFI\-Performance`, which can be found in my GitHub repository here:
.IP "" 4
.IX Item ""
.SS "System integrators"
.IX Subsection "System integrators"
This distribution uses Alien::FFI in fallback mode, meaning if
the system doesn't provide \f(CW\*(C`pkg\-config\*(C'\fR and \f(CW\*(C`libffi\*(C'\fR it will attempt
to download \f(CW\*(C`libffi\*(C'\fR and build it from source. If you are including
Platypus in a larger system (for example a Linux distribution) you
only need to make sure to declare \f(CW\*(C`pkg\-config\*(C'\fR or \f(CW\*(C`pkgconf\*(C'\fR and
the development package for \f(CW\*(C`libffi\*(C'\fR as prereqs for this module.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
.SS "Extending Platypus"
.IX Subsection "Extending Platypus"
.IP "FFI::Platypus::Type" 4
.IX Item "FFI::Platypus::Type"
Type definitions for Platypus.
.IP "\s-1FFI::C\s0" 4
.IX Item "FFI::C"
Interface for defining structured data records for use with
Platypus. It supports C \f(CW\*(C`struct\*(C'\fR, \f(CW\*(C`union\*(C'\fR, nested structures
and arrays of all of those. It only supports passing these
types by reference or pointer, so if you need to pass structured
data by value see FFI::Platypus::Record below.
.IP "FFI::Platypus::Record" 4
.IX Item "FFI::Platypus::Record"
Interface for defining structured data records for use with
Platypus. Included in the Platypus core. Supports pass by
value which is uncommon in C, but frequently used in languages
like Rust and Go. Consider using \s-1FFI::C\s0 instead if you
don't need to pass by value.
.IP "FFI::Platypus::API" 4
.IX Item "FFI::Platypus::API"
The custom types \s-1API\s0 for Platypus.
.IP "FFI::Platypus::Memory" 4
.IX Item "FFI::Platypus::Memory"
Memory functions for \s-1FFI.\s0
.SS "Languages"
.IX Subsection "Languages"
.IP "FFI::Platypus::Lang::C" 4
.IX Item "FFI::Platypus::Lang::C"
Documentation and tools for using Platypus with the C programming
language
.IP "FFI::Platypus::Lang::CPP" 4
.IX Item "FFI::Platypus::Lang::CPP"
Documentation and tools for using Platypus with the \*(C+ programming
language
.IP "FFI::Platypus::Lang::Fortran" 4
.IX Item "FFI::Platypus::Lang::Fortran"
Documentation and tools for using Platypus with Fortran
.IP "FFI::Platypus::Lang::Go" 4
.IX Item "FFI::Platypus::Lang::Go"
Documentation and tools for using Platypus with Go
.IP "FFI::Platypus::Lang::Pascal" 4
.IX Item "FFI::Platypus::Lang::Pascal"
Documentation and tools for using Platypus with Free Pascal
.IP "FFI::Platypus::Lang::Rust" 4
.IX Item "FFI::Platypus::Lang::Rust"
Documentation and tools for using Platypus with the Rust programming
language
.IP "FFI::Platypus::Lang::ASM" 4
.IX Item "FFI::Platypus::Lang::ASM"
Documentation and tools for using Platypus with the Assembly
.IP "FFI::Platypus::Lang::Win32" 4
.IX Item "FFI::Platypus::Lang::Win32"
Documentation and tools for using Platypus with the Win32 \s-1API.\s0
.IP "FFI::Platypus::Lang::Zig" 4
.IX Item "FFI::Platypus::Lang::Zig"
Documentation and tools for using Platypus with the Zig programming
language
.IP "Wasm and Wasm::Wasmtime" 4
.IX Item "Wasm and Wasm::Wasmtime"
Modules for writing WebAssembly bindings in Perl. This allows you to call
functions written in any language supported by WebAssembly. These modules
are also implemented using Platypus.
.SS "Other Tools Related Tools Useful for \s-1FFI\s0"
.IX Subsection "Other Tools Related Tools Useful for FFI"
.IP "FFI::CheckLib" 4
.IX Item "FFI::CheckLib"
Find dynamic libraries in a portable way.
.IP "Convert::Binary::C" 4
.IX Item "Convert::Binary::C"
A great interface for decoding C data structures, including \f(CW\*(C`struct\*(C'\fRs,
\&\f(CW\*(C`enum\*(C'\fRs, \f(CW\*(C`#define\*(C'\fRs and more.
.IP "pack and unpack" 4
.IX Item "pack and unpack"
Native to Perl functions that can be used to decode C \f(CW\*(C`struct\*(C'\fR types.
.IP "C::Scan" 4
.IX Item "C::Scan"
This module can extract constants and other useful objects from C header
files that may be relevant to an \s-1FFI\s0 application. One downside is that
its use may require development packages to be installed.
.SS "Other Foreign Function Interfaces"
.IX Subsection "Other Foreign Function Interfaces"
.IP "Dyn" 4
.IX Item "Dyn"
A wrapper around dyncall , which is itself an alternative to
libffi .
.IP "NativeCall" 4
.IX Item "NativeCall"
Promising interface to Platypus inspired by Raku.
.IP "Win32::API" 4
.IX Item "Win32::API"
Microsoft Windows specific \s-1FFI\s0 style interface.
.IP "\s-1FFI\s0" 4
.IX Item "FFI"
Older, simpler, less featureful \s-1FFI.\s0 It used to be implemented
using \s-1FSF\s0's \f(CW\*(C`ffcall\*(C'\fR. Because \f(CW\*(C`ffcall\*(C'\fR has been unsupported for
some time, I reimplemented this module using FFI::Platypus.
.IP "C::DynaLib" 4
.IX Item "C::DynaLib"
Another \s-1FFI\s0 for Perl that doesn't appear to have worked for a long time.
.IP "C::Blocks" 4
.IX Item "C::Blocks"
Embed a tiny C compiler into your Perl scripts.
.IP "P5NCI" 4
.IX Item "P5NCI"
Yet another \s-1FFI\s0 like interface that does not appear to be supported or
under development anymore.
.SS "Other"
.IX Subsection "Other"
.IP "Alien::FFI" 4
.IX Item "Alien::FFI"
Provides libffi for Platypus during its configuration and build stages.
.SH "ACKNOWLEDGMENTS"
.IX Header "ACKNOWLEDGMENTS"
In addition to the contributors mentioned below, I would like to
acknowledge Brock Wilcox (\s-1AWWAIID\s0) and Meredith Howard (\s-1MHOWARD\s0) whose
work on \f(CW\*(C`FFI::Sweet\*(C'\fR not only helped me get started with \s-1FFI\s0 but
significantly influenced the design of Platypus.
.PP
Dan Book, who goes by Grinnz on \s-1IRC\s0 for answering user questions about
\&\s-1FFI\s0 and Platypus.
.PP
In addition I'd like to thank Alessandro Ghedini (\s-1ALEXBIO\s0) whose work
on another Perl \s-1FFI\s0 library helped drive some of the development ideas
for FFI::Platypus.
.SH "AUTHOR"
.IX Header "AUTHOR"
Author: Graham Ollis
.PP
Contributors:
.PP
Bakkiaraj Murugesan (bakkiaraj)
.PP
Dylan Cali (calid)
.PP
pipcet
.PP
Zaki Mughal (zmughal)
.PP
Fitz Elliott (felliott)
.PP
Vickenty Fesunov (vyf)
.PP
Gregor Herrmann (gregoa)
.PP
Shlomi Fish (shlomif)
.PP
Damyan Ivanov
.PP
Ilya Pavlov (Ilya33)
.PP
Petr Písař (ppisar)
.PP
Mohammad S Anwar (\s-1MANWAR\s0)
.PP
Håkon Hægland (hakonhagland, \s-1HAKONH\s0)
.PP
Meredith (merrilymeredith, \s-1MHOWARD\s0)
.PP
Diab Jerius (\s-1DJERIUS\s0)
.PP
Eric Brine (\s-1IKEGAMI\s0)
.PP
szTheory
.PP
José Joaquín Atria (\s-1JJATRIA\s0)
.PP
Pete Houston (openstrike, \s-1HOUSTON\s0)
.SH "COPYRIGHT AND LICENSE"
.IX Header "COPYRIGHT AND LICENSE"
This software is copyright (c) 2015\-2022 by Graham Ollis.
.PP
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.