.\" Automatically generated by Pod::Man 4.07 (Pod::Simple 3.32) .\" .\" 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 .. .if !\nF .nr F 0 .if \nF>0 \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} .\} .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "FFI::Platypus 3pm" .TH FFI::Platypus 3pm "2016-10-29" "perl v5.24.1" "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 0.45 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use FFI::Platypus; \& \& my $ffi = FFI::Platypus\->new; \& $ffi\->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+, Fortran, Rust, Pascal. Essentially anything that gets compiled into machine code. This implementation uses \f(CW\*(C`libffi\*(C'\fR to accomplish this task. \f(CW\*(C`libffi\*(C'\fR 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 Perl 6" 4 .IX Item "FFI / Platypus could be a bridge to Perl 6" One of those \*(L"other\*(R" languages could be Perl 6 and Perl 6 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, 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. .SH "CONSTRUCTORS" .IX Header "CONSTRUCTORS" .SS "new" .IX Subsection "new" .Vb 1 \& my $ffi = FFI::Platypus\->new(%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 "lib" 4 .IX Item "lib" Either a pathname (string) or a list of pathnames (array ref of strings) to pre-populate the lib attribute. .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". .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); # oly 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 "function" .IX Subsection "function" .Vb 2 \& my $function = $ffi\->function($name => \e@argument_types => $return_type); \& my $function = $ffi\->function($address => \e@argument_types => $return_type); .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_functon\*(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, or modules such as FFI::TinyCC produce machine code at runtime that you can call from Platypus. .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 .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, sub { ... }); \& $ffi\->attach([$c_name => $perl_name] => \e@argument_types => $return_type, sub { ... }); \& $ffi\->attach([$address => $perl_name] => \e@argument_types => $return_type, sub { ... }); .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_functon_name\*(Aq, [\*(Aqint\*(Aq, \*(Aqstring\*(Aq] => \*(Aqstring\*(Aq); \& $ffi\->attach([\*(Aqmy_c_functon_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 .SS "closure" .IX Subsection "closure" .Vb 1 \& my $closure = $ffi\->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. .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 2 \& $ffi\->attach_cast("cast_name", $original_type, $converted_type); \& 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. .SS "sizeof" .IX Subsection "sizeof" .Vb 1 \& my $size = $ffi\->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 "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 "package" .IX Subsection "package" [version 0.15] .PP .Vb 2 \& $ffi\->package($package, $file); # usually _\|_PACKAGE_\|_ and _\|_FILE_\|_ can be used \& $ffi\->package; # autodetect .Ve .PP If you have used 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 "Integer conversions" .IX Subsection "Integer conversions" .Vb 1 \& use FFI::Platypus; \& \& my $ffi = FFI::Platypus\->new; \& $ffi\->lib(undef); \& \& $ffi\->attach(puts => [\*(Aqstring\*(Aq] => \*(Aqint\*(Aq); \& $ffi\->attach(atoi => [\*(Aqstring\*(Aq] => \*(Aqint\*(Aq); \& \& puts(atoi(\*(Aq56\*(Aq)); .Ve .PP \&\fBDiscussion\fR: \f(CW\*(C`puts\*(C'\fR and \f(CW\*(C`atoi\*(C'\fR should be part of the standard C library on all platforms. \f(CW\*(C`puts\*(C'\fR prints a string to standard output, and \f(CW\*(C`atoi\*(C'\fR converts a string to integer. Specifying \f(CW\*(C`undef\*(C'\fR as a library tells Platypus to search the current process for symbols, which includes the standard c library. .SS "libnotify" .IX Subsection "libnotify" .Vb 2 \& use FFI::CheckLib; \& use FFI::Platypus; \& \& # NOTE: I ported this from the like named eg/notify.pl that came with FFI::Raw \& # and it seems to work most of the time, but also seems to SIGSEGV sometimes. \& # I saw the same behavior in the FFI::Raw version, and am not really familiar \& # with the libnotify API to say what is the cause. Patches welcome to fix it. \& \& my $ffi = FFI::Platypus\->new; \& $ffi\->lib(find_lib_or_exit lib => \*(Aqnotify\*(Aq); \& \& $ffi\->attach(notify_init => [\*(Aqstring\*(Aq] => \*(Aqvoid\*(Aq); \& $ffi\->attach(notify_uninit => [] => \*(Aqvoid\*(Aq); \& $ffi\->attach([notify_notification_new => \*(Aqnotify_new\*(Aq] => [\*(Aqstring\*(Aq, \*(Aqstring\*(Aq, \*(Aqstring\*(Aq] => \*(Aqopaque\*(Aq); \& $ffi\->attach([notify_notification_update => \*(Aqnotify_update\*(Aq] => [\*(Aqopaque\*(Aq, \*(Aqstring\*(Aq, \*(Aqstring\*(Aq, \*(Aqstring\*(Aq] => \*(Aqvoid\*(Aq); \& $ffi\->attach([notify_notification_show => \*(Aqnotify_show\*(Aq] => [\*(Aqopaque\*(Aq, \*(Aqopaque\*(Aq] => \*(Aqvoid\*(Aq); \& \& notify_init(\*(AqFFI::Platypus\*(Aq); \& my $n = notify_new(\*(Aq\*(Aq,\*(Aq\*(Aq,\*(Aq\*(Aq); \& notify_update($n, \*(AqFFI::Platypus\*(Aq, \*(AqIt works!!!\*(Aq, \*(Aqmedia\-playback\-start\*(Aq); \& notify_show($n, undef); \& notify_uninit(); .Ve .PP \&\fBDiscussion\fR: libnotify is a desktop \s-1GUI\s0 notification library 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. .PP The most portable way to find the correct name and location of a dynamic library is via the FFI::CheckLib#find_lib family of functions. If you are putting together a \s-1CPAN\s0 distribution, you should also consider using FFI::CheckLib#check_lib_or_exit function in your \f(CW\*(C`Build.PL\*(C'\fR or \&\f(CW\*(C`Makefile.PL\*(C'\fR file (If you are using Dist::Zilla, check out the Dist::Zilla::Plugin::FFI::CheckLib plugin). This will provide a user friendly diagnostic letting the user know that the required library is missing, and reduce the number of bogus \s-1CPAN\s0 testers results that you will get. .PP Also in this example, we rename some of the functions when they are placed into Perl space to save typing: .PP .Vb 3 \& attach [notify_notification_new => \*(Aqnotify_new\*(Aq] \& => [string,string,string] \& => opaque; .Ve .PP When you specify a list reference as the \*(L"name\*(R" of the function the first element is the symbol name as understood by the dynamic library. The second element is the name as it will be placed in Perl space. .PP Later, when we call \f(CW\*(C`notify_new\*(C'\fR: .PP .Vb 1 \& my $n = notify_new(\*(Aq\*(Aq,\*(Aq\*(Aq,\*(Aq\*(Aq); .Ve .PP We are really calling the C function \f(CW\*(C`notify_notification_new\*(C'\fR. .SS "Allocating and freeing memory" .IX Subsection "Allocating and freeing memory" .Vb 2 \& use FFI::Platypus; \& use FFI::Platypus::Memory qw( malloc free memcpy ); \& \& my $ffi = FFI::Platypus\->new; \& my $buffer = malloc 12; \& \& memcpy $buffer, $ffi\->cast(\*(Aqstring\*(Aq => \*(Aqopaque\*(Aq, "hello there"), length "hello there\e0"; \& \& print $ffi\->cast(\*(Aqopaque\*(Aq => \*(Aqstring\*(Aq, $buffer), "\en"; \& \& free $buffer; .Ve .PP \&\fBDiscussion\fR: \f(CW\*(C`malloc\*(C'\fR and \f(CW\*(C`free\*(C'\fR are standard memory allocation functions available from the standard c library and. Interfaces to these and other memory related functions are provided by the FFI::Platypus::Memory module. .SS "structured data records" .IX Subsection "structured data records" .Vb 1 \& package My::UnixTime; \& \& use FFI::Platypus::Record; \& \& record_layout(qw( \& int tm_sec \& int tm_min \& int tm_hour \& int tm_mday \& int tm_mon \& int tm_year \& int tm_wday \& int tm_yday \& int tm_isdst \& long tm_gmtoff \& string tm_zone \& )); \& \& my $ffi = FFI::Platypus\->new; \& $ffi\->lib(undef); \& # define a record class My::UnixTime and alias it to "tm" \& $ffi\->type("record(My::UnixTime)" => \*(Aqtm\*(Aq); \& \& # attach the C localtime function as a constructor \& $ffi\->attach( localtime => [\*(Aqtime_t*\*(Aq] => \*(Aqtm\*(Aq, sub { \& my($inner, $class, $time) = @_; \& $time = time unless defined $time; \& $inner\->(\e$time); \& }); \& \& package main; \& \& # now we can actually use our My::UnixTime class \& my $time = My::UnixTime\->localtime; \& printf "time is %d:%d:%d %s\en", \& $time\->tm_hour, \& $time\->tm_min, \& $time\->tm_sec, \& $time\->tm_zone; .Ve .PP \&\fBDiscussion\fR: C and other machine code languages frequently provide interfaces that include structured data records (known as \*(L"structs\*(R" in C). They sometimes provide an \s-1API\s0 in which you are expected to manipulate these records before and/or after passing them along to C functions. There are a few ways of dealing with such interfaces, but the easiest way is demonstrated here defines a record class using a specific layout. For more details see FFI::Platypus::Record. (FFI::Platypus::Type includes some other ways of manipulating structured data records). .SS "libuuid" .IX Subsection "libuuid" .Vb 3 \& use FFI::CheckLib; \& use FFI::Platypus; \& use FFI::Platypus::Memory qw( malloc free ); \& \& my $ffi = FFI::Platypus\->new; \& $ffi\->lib(find_lib_or_exit lib => \*(Aquuid\*(Aq); \& $ffi\->type(\*(Aqstring(37)\*(Aq => \*(Aquuid_string\*(Aq); \& $ffi\->type(\*(Aqrecord(16)\*(Aq => \*(Aquuid_t\*(Aq); \& \& $ffi\->attach(uuid_generate => [\*(Aquuid_t\*(Aq] => \*(Aqvoid\*(Aq); \& $ffi\->attach(uuid_unparse => [\*(Aquuid_t\*(Aq,\*(Aquuid_string\*(Aq] => \*(Aqvoid\*(Aq); \& \& my $uuid = "\e0" x 16; # uuid_t \& uuid_generate($uuid); \& \& my $string = "\e0" x 37; # 36 bytes to store a UUID string \& # + NUL termination \& uuid_unparse($uuid, $string); \& \& print "$string\en"; .Ve .PP \&\fBDiscussion\fR: libuuid is a library used to generate unique identifiers (\s-1UUID\s0) for objects that may be accessible beyond the local system. The library is or was part of the Linux e2fsprogs package. .PP Knowing the size of objects is sometimes important. In this example, we use the sizeof function to get the size of 16 characters (in this case it is simply 16 bytes). We also know that the strings \&\*(L"deparsed\*(R" by \f(CW\*(C`uuid_unparse\*(C'\fR are exactly 37 bytes. .SS "puts and getpid" .IX Subsection "puts and getpid" .Vb 1 \& use FFI::Platypus; \& \& my $ffi = FFI::Platypus\->new; \& $ffi\->lib(undef); \& \& $ffi\->attach(puts => [\*(Aqstring\*(Aq] => \*(Aqint\*(Aq); \& $ffi\->attach(getpid => [] => \*(Aqint\*(Aq); \& \& puts(getpid()); .Ve .PP \&\fBDiscussion\fR: \f(CW\*(C`puts\*(C'\fR is part of standard C library on all platforms. \&\f(CW\*(C`getpid\*(C'\fR is available on Unix type platforms. .SS "Math library" .IX Subsection "Math library" .Vb 2 \& use FFI::Platypus; \& use FFI::CheckLib; \& \& my $ffi = FFI::Platypus\->new; \& $ffi\->lib(undef); \& $ffi\->attach(puts => [\*(Aqstring\*(Aq] => \*(Aqint\*(Aq); \& $ffi\->attach(fdim => [\*(Aqdouble\*(Aq,\*(Aqdouble\*(Aq] => \*(Aqdouble\*(Aq); \& \& puts(fdim(7.0, 2.0)); \& \& $ffi\->attach(cos => [\*(Aqdouble\*(Aq] => \*(Aqdouble\*(Aq); \& \& puts(cos(2.0)); \& \& $ffi\->attach(fmax => [\*(Aqdouble\*(Aq, \*(Aqdouble\*(Aq] => \*(Aqdouble\*(Aq); \& \& puts(fmax(2.0,3.0)); .Ve .PP \&\fBDiscussion\fR: On \s-1UNIX\s0 the standard c library math functions are frequently provided in a separate library \f(CW\*(C`libm\*(C'\fR, so you could search for those symbols in \*(L"libm.so\*(R", but that won't work on non-UNIX platforms like Microsoft Windows. Fortunately Perl uses the math library so these symbols are already in the current process so you can use \f(CW\*(C`undef\*(C'\fR as the library to find them. .SS "Strings" .IX Subsection "Strings" .Vb 1 \& use FFI::Platypus; \& \& my $ffi = FFI::Platypus\->new; \& $ffi\->lib(undef); \& $ffi\->attach(puts => [\*(Aqstring\*(Aq] => \*(Aqint\*(Aq); \& $ffi\->attach(strlen => [\*(Aqstring\*(Aq] => \*(Aqint\*(Aq); \& \& puts(strlen(\*(Aqsomestring\*(Aq)); \& \& $ffi\->attach(strstr => [\*(Aqstring\*(Aq,\*(Aqstring\*(Aq] => \*(Aqstring\*(Aq); \& \& puts(strstr(\*(Aqsomestring\*(Aq, \*(Aqstring\*(Aq)); \& \& #attach puts => [string] => int; \& \& puts(puts("lol")); \& \& $ffi\->attach(strerror => [\*(Aqint\*(Aq] => \*(Aqstring\*(Aq); \& \& puts(strerror(2)); .Ve .PP \&\fBDiscussion\fR: Strings are not a native type to \f(CW\*(C`libffi\*(C'\fR but the are handled seamlessly by Platypus. .SS "Attach function from pointer" .IX Subsection "Attach function from pointer" .Vb 2 \& use FFI::TinyCC; \& use FFI::Platypus; \& \& my $ffi = FFI::Platypus\->new; \& my $tcc = FFI::TinyCC\->new; \& \& $tcc\->compile_string(q{ \& int \& add(int a, int b) \& { \& return a+b; \& } \& }); \& \& my $address = $tcc\->get_symbol(\*(Aqadd\*(Aq); \& \& $ffi\->attach( [ $address => \*(Aqadd\*(Aq ] => [\*(Aqint\*(Aq,\*(Aqint\*(Aq] => \*(Aqint\*(Aq ); \& \& print add(1,2), "\en"; .Ve .PP \&\fBDiscussion\fR: Sometimes you will have a pointer to a function from a source other than Platypus that you want to call. You can use that address instead of a function name for either of the function or attach methods. In this example we use FFI::TinyCC to compile a short piece of C code and to give us the address of one of its functions, which we then use to create a perl xsub to call it. .PP FFI::TinyCC embeds the Tiny C Compiler (tcc) to provide a just-in-time (\s-1JIT\s0) compilation service for \s-1FFI.\s0 .SS "libzmq" .IX Subsection "libzmq" .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_exit ); \& use FFI::Platypus; \& use FFI::Platypus::Memory qw( malloc ); \& use FFI::Platypus::Buffer qw( scalar_to_buffer buffer_to_scalar ); \& \& my $endpoint = "ipc://zmq\-ffi\-$$"; \& my $ffi = FFI::Platypus\->new; \& \& $ffi\->lib(undef); # for puts \& $ffi\->attach(puts => [\*(Aqstring\*(Aq] => \*(Aqint\*(Aq); \& \& $ffi\->lib(find_lib_or_exit 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); \& puts("libzmq version $major.$minor.$patch"); \& 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); \& \& do { # 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; \& }; \& \& do { # 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); \& my $recv_message = buffer_to_scalar $data_ptr, $size; \& print "recv_message = $recv_message\en"; \& }; .Ve .PP \&\fBDiscussion\fR: O\*/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 Notice that we define three aliases for the \f(CW\*(C`opaque\*(C'\fR type: \&\f(CW\*(C`zmq_context\*(C'\fR, \f(CW\*(C`zmq_socket\*(C'\fR and \f(CW\*(C`zmq_msg_t\*(C'\fR. While this isn't strictly necessary, since Platypus and C treat all three of these types the same, it is useful form of documentation that helps describe the functionality of the interface. .PP Finally we attach the necessary functions, send and receive a message. If you are interested, there is a fully fleshed out O\*/MQ Perl interface implemented using \s-1FFI\s0 called \s-1ZMQ::FFI\s0. .SS "libarchive" .IX Subsection "libarchive" .Vb 3 \& use FFI::Platypus (); \& use FFI::Platypus::API (); \& use FFI::CheckLib (); \& \& # 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 = My::Platypus\->new; \& $ffi\->lib(FFI::CheckLib::find_lib_or_exit lib => \*(Aqarchive\*(Aq); \& \& $ffi\->custom_type(archive => { \& native_type => \*(Aqopaque\*(Aq, \& perl_to_native => sub { ${$_[0]} }, \& native_to_perl => sub { \& # this works because archive_read_new ignores any arguments \& # and we pass in the class name which we can get here. \& my $class = FFI::Platypus::API::arguments_get_string(0); \& bless \e$_[0], $class; \& }, \& }); \& \& $ffi\->custom_type(archive_entry => { \& native_type => \*(Aqopaque\*(Aq, \& perl_to_native => sub { ${$_[0]} }, \& native_to_perl => sub { \& # works likewise for archive_entry objects \& my $class = FFI::Platypus::API::arguments_get_string(0); \& bless \e$_[0], $class, \& }, \& }); \& \& package My::Platypus; \& \& use base qw( FFI::Platypus ); \& \& sub find_symbol \& { \& my($self, $name) = @_; \& my $prefix = lcfirst caller(2); \& $prefix =~ s{([A\-Z])}{"_" . lc $1}eg; \& $self\->SUPER::find_symbol(join \*(Aq_\*(Aq, $prefix, $name); \& } \& \& package Archive; \& \& # base class is "abstract" having no constructor or destructor \& \& $ffi\->attach( error_string => [\*(Aqarchive\*(Aq] => \*(Aqstring\*(Aq ); \& \& package ArchiveRead; \& \& our @ISA = qw( Archive ); \& \& $ffi\->attach( new => [\*(Aqstring\*(Aq] => \*(Aqarchive\*(Aq ); \& $ffi\->attach( [ free => \*(AqDESTROY\*(Aq ] => [\*(Aqarchive\*(Aq] => \*(Aqvoid\*(Aq ); \& $ffi\->attach( support_filter_all => [\*(Aqarchive\*(Aq] => \*(Aqint\*(Aq ); \& $ffi\->attach( support_format_all => [\*(Aqarchive\*(Aq] => \*(Aqint\*(Aq ); \& $ffi\->attach( open_filename => [\*(Aqarchive\*(Aq,\*(Aqstring\*(Aq,\*(Aqsize_t\*(Aq] => \*(Aqint\*(Aq ); \& $ffi\->attach( next_header2 => [\*(Aqarchive\*(Aq, \*(Aqarchive_entry\*(Aq ] => \*(Aqint\*(Aq ); \& $ffi\->attach( data_skip => [\*(Aqarchive\*(Aq] => \*(Aqint\*(Aq ); \& # ... define additional read methods \& \& package ArchiveWrite; \& \& our @ISA = qw( Archive ); \& \& $ffi\->attach( new => [\*(Aqstring\*(Aq] => \*(Aqarchive\*(Aq ); \& $ffi\->attach( [ free => \*(AqDESTROY\*(Aq ] => [\*(Aqarchive\*(Aq] => \*(Aqvoid\*(Aq ); \& # ... define additional write methods \& \& package ArchiveEntry; \& \& $ffi\->attach( new => [\*(Aqstring\*(Aq] => \*(Aqarchive_entry\*(Aq ); \& $ffi\->attach( [ free => \*(AqDESTROY\*(Aq ] => [\*(Aqarchive_entry\*(Aq] => \*(Aqvoid\*(Aq ); \& $ffi\->attach( pathname => [\*(Aqarchive_entry\*(Aq] => \*(Aqstring\*(Aq ); \& # ... define additional entry methods \& \& package main; \& \& 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 \&\fBDiscussion\fR: 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. For more details on custom types see FFI::Platypus::Type and FFI::Platypus::API. .PP Another advanced feature of this example is that we extend the FFI::Platypus class to define our own find_symbol method that prefixes the symbol names depending on the class in which they are defined. This means we can do this when we define a method for Archive: .PP .Vb 1 \& $ffi\->attach( support_filter_all => [\*(Aqarchive\*(Aq] => \*(Aqint\*(Aq ); .Ve .PP Rather than this: .PP .Vb 4 \& $ffi\->attach( \& [ archive_read_support_filter_all => \*(Aqsupport_read_filter_all\*(Aq ] => \& [\*(Aqarchive\*(Aq] => \*(Aqint\*(Aq ); \& ); .Ve .PP If you didn't want to create an entire new class just for this little trick you could also use something like Object::Method to extend \&\f(CW\*(C`find_symbol\*(C'\fR. .SS "bzip2" .IX Subsection "bzip2" .Vb 4 \& use FFI::Platypus 0.20 (); # 0.20 required for using wrappers \& use FFI::CheckLib qw( find_lib_or_die ); \& use FFI::Platypus::Buffer qw( scalar_to_buffer buffer_to_scalar ); \& use FFI::Platypus::Memory qw( malloc free ); \& \& my $ffi = FFI::Platypus\->new; \& $ffi\->lib(find_lib_or_die lib => \*(Aqbz2\*(Aq); \& \& $ffi\->attach( \& [ BZ2_bzBuffToBuffCompress => \*(Aqcompress\*(Aq ] => [ \& \*(Aqopaque\*(Aq, # dest \& \*(Aqunsigned int *\*(Aq, # dest length \& \*(Aqopaque\*(Aq, # source \& \*(Aqunsigned int\*(Aq, # source length \& \*(Aqint\*(Aq, # blockSize100k \& \*(Aqint\*(Aq, # verbosity \& \*(Aqint\*(Aq, # workFactor \& ] => \*(Aqint\*(Aq, \& sub { \& my $sub = shift; \& my($source,$source_length) = scalar_to_buffer $_[0]; \& my $dest_length = int(length($source)*1.01) + 1 + 600; \& my $dest = malloc $dest_length; \& my $r = $sub\->($dest, \e$dest_length, $source, $source_length, 9, 0, 30); \& die "bzip2 error $r" unless $r == 0; \& my $compressed = buffer_to_scalar($dest, $dest_length); \& free $dest; \& $compressed; \& }, \& ); \& \& $ffi\->attach( \& [ BZ2_bzBuffToBuffDecompress => \*(Aqdecompress\*(Aq ] => [ \& \*(Aqopaque\*(Aq, # dest \& \*(Aqunsigned int *\*(Aq, # dest length \& \*(Aqopaque\*(Aq, # source \& \*(Aqunsigned int\*(Aq, # source length \& \*(Aqint\*(Aq, # small \& \*(Aqint\*(Aq, # verbosity \& ] => \*(Aqint\*(Aq, \& sub { \& my $sub = shift; \& my($source, $source_length) = scalar_to_buffer $_[0]; \& my $dest_length = $_[1]; \& my $dest = malloc $dest_length; \& my $r = $sub\->($dest, \e$dest_length, $source, $source_length, 0, 0); \& die "bzip2 error $r" unless $r == 0; \& my $decompressed = buffer_to_scalar($dest, $dest_length); \& free $dest; \& $decompressed; \& }, \& ); \& \& my $original = "hello compression world\en"; \& my $compressed = compress($original); \& print decompress($compressed, length $original); .Ve .PP \&\fBDiscussion\fR: bzip2 is a compression library. For simple one shot attempts at compression/decompression when you expect the original and the result to fit within memory it provides two convenience functions \&\f(CW\*(C`BZ2_bzBuffToBuffCompress\*(C'\fR and \f(CW\*(C`BZ2_bzBuffToBuffDecompress\*(C'\fR. .PP The first four arguments of both of these C functions are identical, and represent two buffers. One buffer is the source, the second is the destination. For the destination, the length is passed in as a pointer to an integer. On input this integer is the size of the destination buffer, and thus the maximum size of the compressed or decompressed data. When the function returns the actual size of compressed or compressed data is stored in this integer. .PP This is normal stuff for C, but in Perl our buffers are scalars and they already know how large they are. In this sort of situation, wrapping the C function in some Perl code can make your interface a little more Perl like. In order to do this, just provide a code reference as the last argument to the \*(L"attach\*(R" method. The first argument to this wrapper will be a code reference to the C function. The Perl arguments will come in after that. This allows you to modify / convert the arguments to conform to the C \s-1API. \s0 What ever value you return from the wrapper function will be returned back to the original caller. .SS "Java" .IX Subsection "Java" Java: .PP .Vb 2 \& // On Linux build .so with \& // % gcj \-fPIC \-shared \-o libexample.so Example.java \& \& public class Example \& { \& public static void print_hello() \& { \& System.out.println("hello world"); \& } \& \& public static int add(int a, int b) \& { \& return a + b; \& } \& } .Ve .PP \&\*(C+: .PP .Vb 4 \& #include \& #include \& #include \& #include \& \& extern "C" void \& gcj_start() \& { \& using namespace java::lang; \& \& JvCreateJavaVM(NULL); \& JvInitClass(&System::class$); \& } \& \& extern "C" void \& gcj_end() \& { \& JvDetachCurrentThread(); \& } .Ve .PP Perl: .PP .Vb 1 \& use FFI::Platypus; \& \& my $ffi = FFI::Platypus\->new; \& $ffi\->lib(\*(Aq./libexample.so\*(Aq); \& \& # Java methods are mangled by gcj using the same format as g++ \& \& $ffi\->attach( \& [ _ZN7Example11print_helloEJvv => \*(Aqprint_hello\*(Aq ] => [] => \*(Aqvoid\*(Aq \& ); \& \& $ffi\->attach( \& [ _ZN7Example3addEJiii => \*(Aqadd\*(Aq ] => [\*(Aqint\*(Aq, \*(Aqint\*(Aq] => \*(Aqint\*(Aq \& ); \& \& # Initialize the Java runtime \& \& $ffi\->function( gcj_start => [] => \*(Aqvoid\*(Aq )\->call; \& \& print_hello(); \& print add(1,2), "\en"; \& \& # Wind the java runtime down \& \& $ffi\->function( gcj_end => [] => \*(Aqvoid\*(Aq )\->call; .Ve .PP Makefile: .PP .Vb 5 \& GCJ=gcj \& CXX=g++ \& CFLAGS=\-fPIC \& LDFLAGS=\-shared \& RM=rm \-f \& \& libexample.so: between.o Example.o \& $(GCJ) $(LDFLAGS) \-o libexample.so between.o Example.o \& \& between.o: between.cpp \& $(CXX) $(CFLAGS) \-c \-o between.o between.cpp \& \& Example.o: Example.java \& $(GCJ) $(CFLAGS) \-c \-o Example.o Example.java \& \& clean: \& $(RM) *.o *.so .Ve .PP Output: .PP .Vb 7 \& % make \& g++ \-fPIC \-c \-o between.o between.cpp \& gcj \-fPIC \-c \-o Example.o Example.java \& gcj \-shared \-o libexample.so between.o Example.o \& % perl example.pl \& hello world \& 3 .Ve .PP \&\fBDiscussion\fR: You can't call Java .class files directly from \s-1FFI / \s0 Platypus, but you can compile Java source and .class files into a shared library using the \s-1GNU\s0 Java Compiler \f(CW\*(C`gcj\*(C'\fR. Because we are calling Java functions from a program (Perl!) that was not started from a Java \&\f(CW\*(C`main()\*(C'\fR we have to initialize the Java runtime ourselves (details ). This can most easily be accomplished from \*(C+. .PP The \s-1GNU\s0 Java Compiler uses the same format to mangle method names as \s-1GNU \&\*(C+. \s0 The \*(C+ plugin for handles this more transparently by extracting the symbols from the shared library and using either FFI::Platypus::Lang::CPP::Demangle::XS or \f(CW\*(C`c++filt\*(C'\fR to determined the unmangled names. .PP Although the Java source is compiled ahead of time with optimizations, it will not necessarily perform better than a real \s-1JVM\s0 just because it is compiled. In fact the gcj developers warn than gcj will optimize Java source better than Java .class files. The \s-1GNU\s0 Java Compiler also lags behind modern Java. .PP Even so this enables you to call Java from Perl and potentially other Java based languages such as Scala, Groovy or JRuby. .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" Like Google's Go. Although I believe that \s-1XS\s0 won't help in this regard. .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 that can't be understood by gcj. .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 \f(CW\*(C`Build.PL\*(C'\fR and \f(CW\*(C`cpanfile\*(C'\fR files 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 Build.PL \& % ./Build \& % ./Build libtest \& % 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\s0" 4 .IX Item "FFI_PLATYPUS_DEBUG" Build the \s-1XS\s0 code portion of Platypus with \-g3 instead of what ever optimizing flags that your Perl normally uses. This is useful if you need to debug the C or \s-1XS\s0 code that comes with Platypus, but do not have a debugging Perl. .Sp .Vb 1 \& % env FFI_PLATYPUS_DEBUG=1 perl Build.PL \& \& \& DEBUG: \& \- $Config{lddlflags} = \-shared \-O2 \-L/usr/local/lib \-fstack\-protector \& + $Config{lddlflags} = \-shared \-g3 \-L/usr/local/lib \-fstack\-protector \& \- $Config{optimize} = \-O2 \& + $Config{optimize} = \-g3 \& \& \& Created MYMETA.yml and MYMETA.json \& Creating new \*(AqBuild\*(Aq script for \*(AqFFI\-Platypus\*(Aq version \*(Aq0.10\*(Aq .Ve .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 1 \& % env FFI_PLATYPUS_DEBUG_FAKE32=1 perl Build.PL \& \& \& DEBUG_FAKE32: \& + making Math::Int64 a prerequisite (not normally done on 64 bit Perls) \& + using Math::Int64\*(Aqs C API to manipulate 64 bit values (not normally done on 64 bit Perls) \& \& Created MYMETA.yml and MYMETA.json \& Creating new \*(AqBuild\*(Aq script for \*(AqFFI\-Platypus\*(Aq version \*(Aq0.10\*(Aq .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`Build.PL\*(C'\fR: .Sp .Vb 1 \& % env FFI_PLATYPUS_NO_ALLOCA=1 perl Build.PL \& \& \& NO_ALLOCA: \& + alloca() will not be used, even if your platform supports it. \& \& \& Created MYMETA.yml and MYMETA.json \& Creating new \*(AqBuild\*(Aq script for \*(AqFFI\-Platypus\*(Aq version \*(Aq0.10\*(Aq .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" If you are including Platypus in a larger system (for example a Linux distribution), and you already have libffi as part of your system, you may be interested in Alt::Alien::FFI::System. This is an alternative to Alien::FFI that does not require Alien::Base. In fact it has zero non-Core dependencies, and doesn't even need to be installed. Simply include Alt::Alien::FFI::System's \f(CW\*(C`lib\*(C'\fR directory in your \&\f(CW\*(C`PERL5LIB\*(C'\fR path when you build Platypus. For example: .PP .Vb 2 \& % export PERL5LIB=/path/to/Alt\-Alien\-FFI\-System/lib \& % cpanm FFI::Platypus .Ve .SH "SEE ALSO" .IX Header "SEE ALSO" .IP "NativeCall" 4 .IX Item "NativeCall" Promising interface to Platypus inspired by Perl 6. .IP "FFI::Platypus::Type" 4 .IX Item "FFI::Platypus::Type" Type definitions for Platypus. .IP "FFI::Platypus::Record" 4 .IX Item "FFI::Platypus::Record" Define structured data records (C \*(L"structs\*(R") for use with Platypus. .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 .IP "FFI::CheckLib" 4 .IX Item "FFI::CheckLib" Find dynamic libraries in a portable way. .IP "Module::Build::FFI" 4 .IX Item "Module::Build::FFI" Bundle C code with your \s-1FFI\s0 extension. .IP "FFI::TinyCC" 4 .IX Item "FFI::TinyCC" \&\s-1JIT\s0 compiler for \s-1FFI.\s0 .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::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 "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. .IP "FFI::Raw" 4 .IX Item "FFI::Raw" Alternate interface to libffi with fewer features. It notably lacks the ability to create real xsubs, which may make FFI::Platypus much faster. Also lacking are pointers to native types, arrays and custom types. In its favor, it has been around for longer that Platypus, and has been battle tested to some success. .IP "Win32::API" 4 .IX Item "Win32::API" Microsoft Windows specific \s-1FFI\s0 style interface. .IP "Ctypes " 4 .IX Item "Ctypes " Ctypes was intended as a \s-1FFI\s0 style interface for Perl, but was never part of \s-1CPAN,\s0 and at least the last time I tried it did not work with recent versions of Perl. .IP "\s-1FFI\s0" 4 .IX Item "FFI" Foreign function interface based on (nomenclature is everything) \s-1FSF\s0's \&\f(CW\*(C`ffcall\*(C'\fR. It hasn't worked for quite some time, and \f(CW\*(C`ffcall\*(C'\fR is no longer supported or distributed. .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 "Alien::FFI" 4 .IX Item "Alien::FFI" Provides libffi for Platypus during its configuration and build stages. .IP "Alt::Alien::FFI::System" 4 .IX Item "Alt::Alien::FFI::System" An alternative for Alien::FFI intended mainly for system integrators. .IP "P5NCI" 4 .IX Item "P5NCI" Yet another \s-1FFI\s0 like interface that does not appear to be supported or under development anymore. .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 FFI::Sweet not only helped me get started with \s-1FFI\s0 but significantly influenced the design of Platypus. .PP In addition I'd like to thank Alessandro Ghedini (\s-1ALEXBIO\s0) who was always responsive to bug reports and pull requests for FFI::Raw, which was important in the development of the ideas on which Platypus is based. .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) .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2015 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.