| 1 |
NAME |
| 2 |
|
| 3 |
FFI::Platypus - Write Perl bindings to non-Perl libraries with FFI. No |
| 4 |
XS required. |
| 5 |
|
| 6 |
VERSION |
| 7 |
|
| 8 |
version 2.11 |
| 9 |
|
| 10 |
SYNOPSIS |
| 11 |
|
| 12 |
use FFI::Platypus 2.00; |
| 13 |
|
| 14 |
# for all new code you should use api => 2 |
| 15 |
my $ffi = FFI::Platypus->new( |
| 16 |
api => 2, |
| 17 |
lib => undef, # search libc |
| 18 |
); |
| 19 |
|
| 20 |
# call dynamically |
| 21 |
$ffi->function( puts => ['string'] => 'int' )->call("hello world"); |
| 22 |
|
| 23 |
# attach as a xsub and call (much faster) |
| 24 |
$ffi->attach( puts => ['string'] => 'int' ); |
| 25 |
puts("hello world"); |
| 26 |
|
| 27 |
DESCRIPTION |
| 28 |
|
| 29 |
Platypus is a library for creating interfaces to machine code libraries |
| 30 |
written in languages like C, C++, Go, Fortran, Rust, Pascal. |
| 31 |
Essentially anything that gets compiled into machine code. This |
| 32 |
implementation uses libffi <https://sourceware.org/libffi/> to |
| 33 |
accomplish this task. libffi is battle tested by a number of other |
| 34 |
scripting and virtual machine languages, such as Python and Ruby to |
| 35 |
serve a similar role. There are a number of reasons why you might want |
| 36 |
to write an extension with Platypus instead of XS: |
| 37 |
|
| 38 |
FFI / Platypus does not require messing with the guts of Perl |
| 39 |
|
| 40 |
XS is less of an API and more of the guts of perl splayed out to do |
| 41 |
whatever you want. That may at times be very powerful, but it can |
| 42 |
also be a frustrating exercise in hair pulling. |
| 43 |
|
| 44 |
FFI / Platypus is portable |
| 45 |
|
| 46 |
Lots of languages have FFI interfaces, and it is subjectively easier |
| 47 |
to port an extension written in FFI in Perl or another language to |
| 48 |
FFI in another language or Perl. One goal of the Platypus Project is |
| 49 |
to reduce common interface specifications to a common format like |
| 50 |
JSON that could be shared between different languages. |
| 51 |
|
| 52 |
FFI / Platypus could be a bridge to Raku |
| 53 |
|
| 54 |
One of those "other" languages could be Raku and Raku already has an |
| 55 |
FFI interface I am told. |
| 56 |
|
| 57 |
FFI / Platypus can be reimplemented |
| 58 |
|
| 59 |
In a bright future with multiple implementations of Perl 5, each |
| 60 |
interpreter will have its own implementation of Platypus, allowing |
| 61 |
extensions to be written once and used on multiple platforms, in much |
| 62 |
the same way that Ruby-FFI extensions can be use in Ruby, JRuby and |
| 63 |
Rubinius. |
| 64 |
|
| 65 |
FFI / Platypus is pure perl (sorta) |
| 66 |
|
| 67 |
One Platypus script or module works on any platform where the |
| 68 |
libraries it uses are available. That means you can deploy your |
| 69 |
Platypus script in a shared filesystem where they may be run on |
| 70 |
different platforms. It also means that Platypus modules do not need |
| 71 |
to be installed in the platform specific Perl library path. |
| 72 |
|
| 73 |
FFI / Platypus is not C or C++ centric |
| 74 |
|
| 75 |
XS is implemented primarily as a bunch of C macros, which requires at |
| 76 |
least some understanding of C, the C pre-processor, and some C++ |
| 77 |
caveats (since on some platforms Perl is compiled and linked with a |
| 78 |
C++ compiler). Platypus on the other hand could be used to call other |
| 79 |
compiled languages, like Fortran, Go, Rust, Pascal, C++, or even |
| 80 |
assembly, allowing you to focus on your strengths. |
| 81 |
|
| 82 |
FFI / Platypus does not require a parser |
| 83 |
|
| 84 |
Inline isolates the extension developer from XS to some extent, but |
| 85 |
it also requires a parser. The various Inline language bindings are a |
| 86 |
great technical achievement, but I think writing a parser for every |
| 87 |
language that you want to interface with is a bit of an anti-pattern. |
| 88 |
|
| 89 |
This document consists of an API reference, a set of examples, some |
| 90 |
support and development (for contributors) information. If you are new |
| 91 |
to Platypus or FFI, you may want to skip down to the EXAMPLES to get a |
| 92 |
taste of what you can do with Platypus. |
| 93 |
|
| 94 |
Platypus has extensive documentation of types at FFI::Platypus::Type |
| 95 |
and its custom types API at FFI::Platypus::API. |
| 96 |
|
| 97 |
You are strongly encouraged to use API level 2 for all new code. There |
| 98 |
are a number of improvements and design fixes that you get for free. |
| 99 |
You should even consider updating existing modules to use API level 2 |
| 100 |
where feasible. How do I do that you might ask? Simply pass in the API |
| 101 |
level to the platypus constructor. |
| 102 |
|
| 103 |
my $ffi = FFI::Platypus->new( api => 2 ); |
| 104 |
|
| 105 |
The Platypus documentation has already been updated to assume API level |
| 106 |
1. |
| 107 |
|
| 108 |
CONSTRUCTORS |
| 109 |
|
| 110 |
new |
| 111 |
|
| 112 |
my $ffi = FFI::Platypus->new( api => 2, %options); |
| 113 |
|
| 114 |
Create a new instance of FFI::Platypus. |
| 115 |
|
| 116 |
Any types defined with this instance will be valid for this instance |
| 117 |
only, so you do not need to worry about stepping on the toes of other |
| 118 |
CPAN FFI / Platypus Authors. |
| 119 |
|
| 120 |
Any functions found will be out of the list of libraries specified with |
| 121 |
the lib attribute. |
| 122 |
|
| 123 |
options |
| 124 |
|
| 125 |
api |
| 126 |
|
| 127 |
[version 0.91] |
| 128 |
|
| 129 |
Sets the API level. The recommended value for all new code is 2. The |
| 130 |
Platypus documentation assumes API level 2 except for a few places |
| 131 |
that specifically document older versions. You should only use a |
| 132 |
lower value for a legacy code base that cannot be migrated to a newer |
| 133 |
API level. Legal values are: |
| 134 |
|
| 135 |
0 |
| 136 |
|
| 137 |
Original API level. See FFI::Platypus::TypeParser::Version0 for |
| 138 |
details on the differences. |
| 139 |
|
| 140 |
1 |
| 141 |
|
| 142 |
Enable version 1 API type parser which allows pass-by-value records |
| 143 |
and type decoration on basic types. |
| 144 |
|
| 145 |
2 |
| 146 |
|
| 147 |
Enable version 2 API. The Platypus documentation assumes this api |
| 148 |
level is set. |
| 149 |
|
| 150 |
API version 2 is identical to version 1, except: |
| 151 |
|
| 152 |
Pointer functions that return NULL will return undef instead of |
| 153 |
empty list |
| 154 |
|
| 155 |
This fixes a long standing design bug in Platypus. |
| 156 |
|
| 157 |
Array references may be passed to pointer argument types |
| 158 |
|
| 159 |
This replicates the behavior of array argument types with no |
| 160 |
size. So the types sint8* and sint8[] behave identically when an |
| 161 |
array reference is passed in. They differ in that, as before, you |
| 162 |
can pass a scalar reference into type sint8*. |
| 163 |
|
| 164 |
The fixed string type can be specified without pointer modifier |
| 165 |
|
| 166 |
That is you can use string(10) instead of string(10)* as you were |
| 167 |
previously able to in API 0. |
| 168 |
|
| 169 |
lib |
| 170 |
|
| 171 |
Either a pathname (string) or a list of pathnames (array ref of |
| 172 |
strings) to pre-populate the lib attribute. Use [undef] to search the |
| 173 |
current process for symbols. |
| 174 |
|
| 175 |
0.48 |
| 176 |
|
| 177 |
undef (without the array reference) can be used to search the current |
| 178 |
process for symbols. |
| 179 |
|
| 180 |
ignore_not_found |
| 181 |
|
| 182 |
[version 0.15] |
| 183 |
|
| 184 |
Set the ignore_not_found attribute. |
| 185 |
|
| 186 |
lang |
| 187 |
|
| 188 |
[version 0.18] |
| 189 |
|
| 190 |
Set the lang attribute. |
| 191 |
|
| 192 |
ATTRIBUTES |
| 193 |
|
| 194 |
lib |
| 195 |
|
| 196 |
$ffi->lib($path1, $path2, ...); |
| 197 |
my @paths = $ffi->lib; |
| 198 |
|
| 199 |
The list of libraries to search for symbols in. |
| 200 |
|
| 201 |
The most portable and reliable way to find dynamic libraries is by |
| 202 |
using FFI::CheckLib, like this: |
| 203 |
|
| 204 |
use FFI::CheckLib 0.06; |
| 205 |
$ffi->lib(find_lib_or_die lib => 'archive'); |
| 206 |
# finds libarchive.so on Linux |
| 207 |
# libarchive.bundle on OS X |
| 208 |
# libarchive.dll (or archive.dll) on Windows |
| 209 |
# cygarchive-13.dll on Cygwin |
| 210 |
# ... |
| 211 |
# and will die if it isn't found |
| 212 |
|
| 213 |
FFI::CheckLib has a number of options, such as checking for specific |
| 214 |
symbols, etc. You should consult the documentation for that module. |
| 215 |
|
| 216 |
As a special case, if you add undef as a "library" to be searched, |
| 217 |
Platypus will also search the current process for symbols. This is |
| 218 |
mostly useful for finding functions in the standard C library, without |
| 219 |
having to know the name of the standard c library for your platform (as |
| 220 |
it turns out it is different just about everywhere!). |
| 221 |
|
| 222 |
You may also use the "find_lib" method as a shortcut: |
| 223 |
|
| 224 |
$ffi->find_lib( lib => 'archive' ); |
| 225 |
|
| 226 |
ignore_not_found |
| 227 |
|
| 228 |
[version 0.15] |
| 229 |
|
| 230 |
$ffi->ignore_not_found(1); |
| 231 |
my $ignore_not_found = $ffi->ignore_not_found; |
| 232 |
|
| 233 |
Normally the attach and function methods will throw an exception if it |
| 234 |
cannot find the name of the function you provide it. This will change |
| 235 |
the behavior such that function will return undef when the function is |
| 236 |
not found and attach will ignore functions that are not found. This is |
| 237 |
useful when you are writing bindings to a library and have many |
| 238 |
optional functions and you do not wish to wrap every call to function |
| 239 |
or attach in an eval. |
| 240 |
|
| 241 |
lang |
| 242 |
|
| 243 |
[version 0.18] |
| 244 |
|
| 245 |
$ffi->lang($language); |
| 246 |
|
| 247 |
Specifies the foreign language that you will be interfacing with. The |
| 248 |
default is C. The foreign language specified with this attribute |
| 249 |
changes the default native types (for example, if you specify Rust, you |
| 250 |
will get i32 as an alias for sint32 instead of int as you do with C). |
| 251 |
|
| 252 |
If the foreign language plugin supports it, this will also enable |
| 253 |
Platypus to find symbols using the demangled names (for example, if you |
| 254 |
specify CPP for C++ you can use method names like Foo::get_bar() with |
| 255 |
"attach" or "function". |
| 256 |
|
| 257 |
api |
| 258 |
|
| 259 |
[version 1.11] |
| 260 |
|
| 261 |
my $level = $ffi->api; |
| 262 |
|
| 263 |
Returns the API level of the Platypus instance. |
| 264 |
|
| 265 |
METHODS |
| 266 |
|
| 267 |
type |
| 268 |
|
| 269 |
$ffi->type($typename); |
| 270 |
$ffi->type($typename => $alias); |
| 271 |
|
| 272 |
Define a type. The first argument is the native or C name of the type. |
| 273 |
The second argument (optional) is an alias name that you can use to |
| 274 |
refer to this new type. See FFI::Platypus::Type for legal type |
| 275 |
definitions. |
| 276 |
|
| 277 |
Examples: |
| 278 |
|
| 279 |
$ffi->type('sint32'); # only checks to see that sint32 is a valid type |
| 280 |
$ffi->type('sint32' => 'myint'); # creates an alias myint for sint32 |
| 281 |
$ffi->type('bogus'); # dies with appropriate diagnostic |
| 282 |
|
| 283 |
custom_type |
| 284 |
|
| 285 |
$ffi->custom_type($alias => { |
| 286 |
native_type => $native_type, |
| 287 |
native_to_perl => $coderef, |
| 288 |
perl_to_native => $coderef, |
| 289 |
perl_to_native_post => $coderef, |
| 290 |
}); |
| 291 |
|
| 292 |
Define a custom type. See FFI::Platypus::Type#Custom-Types for details. |
| 293 |
|
| 294 |
load_custom_type |
| 295 |
|
| 296 |
$ffi->load_custom_type($name => $alias, @type_args); |
| 297 |
|
| 298 |
Load the custom type defined in the module $name, and make an alias |
| 299 |
$alias. If the custom type requires any arguments, they may be passed |
| 300 |
in as @type_args. See FFI::Platypus::Type#Custom-Types for details. |
| 301 |
|
| 302 |
If $name contains :: then it will be assumed to be a fully qualified |
| 303 |
package name. If not, then FFI::Platypus::Type:: will be prepended to |
| 304 |
it. |
| 305 |
|
| 306 |
types |
| 307 |
|
| 308 |
my @types = $ffi->types; |
| 309 |
my @types = FFI::Platypus->types; |
| 310 |
|
| 311 |
Returns the list of types that FFI knows about. This will include the |
| 312 |
native libffi types (example: sint32, opaque and double) and the normal |
| 313 |
C types (example: unsigned int, uint32_t), any types that you have |
| 314 |
defined using the type method, and custom types. |
| 315 |
|
| 316 |
The list of types that Platypus knows about varies somewhat from |
| 317 |
platform to platform, FFI::Platypus::Type includes a list of the core |
| 318 |
types that you can always count on having access to. |
| 319 |
|
| 320 |
It can also be called as a class method, in which case, no user defined |
| 321 |
or custom types will be included in the list. |
| 322 |
|
| 323 |
type_meta |
| 324 |
|
| 325 |
my $meta = $ffi->type_meta($type_name); |
| 326 |
my $meta = FFI::Platypus->type_meta($type_name); |
| 327 |
|
| 328 |
Returns a hash reference with the meta information for the given type. |
| 329 |
|
| 330 |
It can also be called as a class method, in which case, you won't be |
| 331 |
able to get meta data on user defined types. |
| 332 |
|
| 333 |
The format of the meta data is implementation dependent and subject to |
| 334 |
change. It may be useful for display or debugging. |
| 335 |
|
| 336 |
Examples: |
| 337 |
|
| 338 |
my $meta = $ffi->type_meta('int'); # standard int type |
| 339 |
my $meta = $ffi->type_meta('int[64]'); # array of 64 ints |
| 340 |
$ffi->type('int[128]' => 'myintarray'); |
| 341 |
my $meta = $ffi->type_meta('myintarray'); # array of 128 ints |
| 342 |
|
| 343 |
mangler |
| 344 |
|
| 345 |
$ffi->mangler(\&mangler); |
| 346 |
|
| 347 |
Specify a customer mangler to be used for symbol lookup. This is |
| 348 |
usually useful when you are writing bindings for a library where all of |
| 349 |
the functions have the same prefix. Example: |
| 350 |
|
| 351 |
$ffi->mangler(sub { |
| 352 |
my($symbol) = @_; |
| 353 |
return "foo_$symbol"; |
| 354 |
}); |
| 355 |
|
| 356 |
$ffi->function( get_bar => [] => 'int' ); # attaches foo_get_bar |
| 357 |
|
| 358 |
my $f = $ffi->function( set_baz => ['int'] => 'void' ); |
| 359 |
$f->call(22); # calls foo_set_baz |
| 360 |
|
| 361 |
function |
| 362 |
|
| 363 |
my $function = $ffi->function($name => \@argument_types => $return_type); |
| 364 |
my $function = $ffi->function($address => \@argument_types => $return_type); |
| 365 |
my $function = $ffi->function($name => \@argument_types => $return_type, \&wrapper); |
| 366 |
my $function = $ffi->function($address => \@argument_types => $return_type, \&wrapper); |
| 367 |
|
| 368 |
Returns an object that is similar to a code reference in that it can be |
| 369 |
called like one. |
| 370 |
|
| 371 |
Caveat: many situations require a real code reference, so at the price |
| 372 |
of a performance penalty you can get one like this: |
| 373 |
|
| 374 |
my $function = $ffi->function(...); |
| 375 |
my $coderef = sub { $function->(@_) }; |
| 376 |
|
| 377 |
It may be better, and faster to create a real Perl function using the |
| 378 |
attach method. |
| 379 |
|
| 380 |
In addition to looking up a function by name you can provide the |
| 381 |
address of the symbol yourself: |
| 382 |
|
| 383 |
my $address = $ffi->find_symbol('my_function'); |
| 384 |
my $function = $ffi->function($address => ...); |
| 385 |
|
| 386 |
Under the covers, function uses find_symbol when you provide it with a |
| 387 |
name, but it is useful to keep this in mind as there are alternative |
| 388 |
ways of obtaining a functions address. Example: a C function could |
| 389 |
return the address of another C function that you might want to call. |
| 390 |
|
| 391 |
[version 0.76] |
| 392 |
|
| 393 |
If the last argument is a code reference, then it will be used as a |
| 394 |
wrapper around the function when called. The first argument to the |
| 395 |
wrapper will be the inner function, or if it is later attached an xsub. |
| 396 |
This can be used if you need to verify/modify input/output data. |
| 397 |
|
| 398 |
Examples: |
| 399 |
|
| 400 |
my $function = $ffi->function('my_function_name', ['int', 'string'] => 'string'); |
| 401 |
my $return_string = $function->(1, "hi there"); |
| 402 |
|
| 403 |
[version 0.91] |
| 404 |
|
| 405 |
my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => $return_type); |
| 406 |
my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => $return_type, \&wrapper); |
| 407 |
my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types); |
| 408 |
my $function = $ffi->function( $name => \@fixed_argument_types => \@var_argument_types => \&wrapper); |
| 409 |
|
| 410 |
Version 0.91 and later allows you to creat functions for c variadic |
| 411 |
functions (such as printf, scanf, etc) which can take a variable number |
| 412 |
of arguments. The first set of arguments are the fixed set, the second |
| 413 |
set are the variable arguments to bind with. The variable argument |
| 414 |
types must be specified in order to create a function object, so if you |
| 415 |
need to call variadic function with different set of arguments then you |
| 416 |
will need to create a new function object each time: |
| 417 |
|
| 418 |
# int printf(const char *fmt, ...); |
| 419 |
$ffi->function( printf => ['string'] => ['int'] => 'int' ) |
| 420 |
->call("print integer %d\n", 42); |
| 421 |
$ffi->function( printf => ['string'] => ['string'] => 'int' ) |
| 422 |
->call("print string %s\n", 'platypus'); |
| 423 |
|
| 424 |
Some older versions of libffi and possibly some platforms may not |
| 425 |
support variadic functions. If you try to create a one, then an |
| 426 |
exception will be thrown. |
| 427 |
|
| 428 |
[version 1.26] |
| 429 |
|
| 430 |
If the return type is omitted then void will be the assumed return |
| 431 |
type. |
| 432 |
|
| 433 |
attach |
| 434 |
|
| 435 |
$ffi->attach($name => \@argument_types => $return_type); |
| 436 |
$ffi->attach([$c_name => $perl_name] => \@argument_types => $return_type); |
| 437 |
$ffi->attach([$address => $perl_name] => \@argument_types => $return_type); |
| 438 |
$ffi->attach($name => \@argument_types => $return_type, \&wrapper); |
| 439 |
$ffi->attach([$c_name => $perl_name] => \@argument_types => $return_type, \&wrapper); |
| 440 |
$ffi->attach([$address => $perl_name] => \@argument_types => $return_type, \&wrapper); |
| 441 |
|
| 442 |
Find and attach a C function as a real live Perl xsub. The advantage of |
| 443 |
attaching a function over using the function method is that it is much |
| 444 |
much much faster since no object resolution needs to be done. The |
| 445 |
disadvantage is that it locks the function and the FFI::Platypus |
| 446 |
instance into memory permanently, since there is no way to deallocate |
| 447 |
an xsub. |
| 448 |
|
| 449 |
If just one $name is given, then the function will be attached in Perl |
| 450 |
with the same name as it has in C. The second form allows you to give |
| 451 |
the Perl function a different name. You can also provide an address |
| 452 |
(the third form), just like with the function method. |
| 453 |
|
| 454 |
Examples: |
| 455 |
|
| 456 |
$ffi->attach('my_function_name', ['int', 'string'] => 'string'); |
| 457 |
$ffi->attach(['my_c_function_name' => 'my_perl_function_name'], ['int', 'string'] => 'string'); |
| 458 |
my $string1 = my_function_name($int); |
| 459 |
my $string2 = my_perl_function_name($int); |
| 460 |
|
| 461 |
[version 0.20] |
| 462 |
|
| 463 |
If the last argument is a code reference, then it will be used as a |
| 464 |
wrapper around the attached xsub. The first argument to the wrapper |
| 465 |
will be the inner xsub. This can be used if you need to verify/modify |
| 466 |
input/output data. |
| 467 |
|
| 468 |
Examples: |
| 469 |
|
| 470 |
$ffi->attach('my_function', ['int', 'string'] => 'string', sub { |
| 471 |
my($my_function_xsub, $integer, $string) = @_; |
| 472 |
$integer++; |
| 473 |
$string .= " and another thing"; |
| 474 |
my $return_string = $my_function_xsub->($integer, $string); |
| 475 |
$return_string =~ s/Belgium//; # HHGG remove profanity |
| 476 |
$return_string; |
| 477 |
}); |
| 478 |
|
| 479 |
[version 0.91] |
| 480 |
|
| 481 |
$ffi->attach($name => \@fixed_argument_types => \@var_argument_types, $return_type); |
| 482 |
$ffi->attach($name => \@fixed_argument_types => \@var_argument_types, $return_type, \&wrapper); |
| 483 |
|
| 484 |
As of version 0.91 you can attach a variadic functions, if it is |
| 485 |
supported by the platform / libffi that you are using. For details see |
| 486 |
the function documentation. If not supported by the implementation then |
| 487 |
an exception will be thrown. |
| 488 |
|
| 489 |
closure |
| 490 |
|
| 491 |
my $closure = $ffi->closure($coderef); |
| 492 |
my $closure = FFI::Platypus->closure($coderef); |
| 493 |
|
| 494 |
Prepares a code reference so that it can be used as a FFI closure (a |
| 495 |
Perl subroutine that can be called from C code). For details on |
| 496 |
closures, see FFI::Platypus::Type#Closures and FFI::Platypus::Closure. |
| 497 |
|
| 498 |
cast |
| 499 |
|
| 500 |
my $converted_value = $ffi->cast($original_type, $converted_type, $original_value); |
| 501 |
|
| 502 |
The cast function converts an existing $original_value of type |
| 503 |
$original_type into one of type $converted_type. Not all types are |
| 504 |
supported, so care must be taken. For example, to get the address of a |
| 505 |
string, you can do this: |
| 506 |
|
| 507 |
my $address = $ffi->cast('string' => 'opaque', $string_value); |
| 508 |
|
| 509 |
Something that won't work is trying to cast an array to anything: |
| 510 |
|
| 511 |
my $address = $ffi->cast('int[10]' => 'opaque', \@list); # WRONG |
| 512 |
|
| 513 |
attach_cast |
| 514 |
|
| 515 |
$ffi->attach_cast("cast_name", $original_type, $converted_type); |
| 516 |
$ffi->attach_cast("cast_name", $original_type, $converted_type, \&wrapper); |
| 517 |
my $converted_value = cast_name($original_value); |
| 518 |
|
| 519 |
This function attaches a cast as a permanent xsub. This will make it |
| 520 |
faster and may be useful if you are calling a particular cast a lot. |
| 521 |
|
| 522 |
[version 1.26] |
| 523 |
|
| 524 |
A wrapper may be added as the last argument to attach_cast and works |
| 525 |
just like the wrapper for attach and function methods. |
| 526 |
|
| 527 |
sizeof |
| 528 |
|
| 529 |
my $size = $ffi->sizeof($type); |
| 530 |
my $size = FFI::Platypus->sizeof($type); |
| 531 |
|
| 532 |
Returns the total size of the given type in bytes. For example to get |
| 533 |
the size of an integer: |
| 534 |
|
| 535 |
my $intsize = $ffi->sizeof('int'); # usually 4 |
| 536 |
my $longsize = $ffi->sizeof('long'); # usually 4 or 8 depending on platform |
| 537 |
|
| 538 |
You can also get the size of arrays |
| 539 |
|
| 540 |
my $intarraysize = $ffi->sizeof('int[64]'); # usually 4*64 |
| 541 |
my $intarraysize = $ffi->sizeof('long[64]'); # usually 4*64 or 8*64 |
| 542 |
# depending on platform |
| 543 |
|
| 544 |
Keep in mind that "pointer" types will always be the pointer / word |
| 545 |
size for the platform that you are using. This includes strings, opaque |
| 546 |
and pointers to other types. |
| 547 |
|
| 548 |
This function is not very fast, so you might want to save this value as |
| 549 |
a constant, particularly if you need the size in a loop with many |
| 550 |
iterations. |
| 551 |
|
| 552 |
alignof |
| 553 |
|
| 554 |
[version 0.21] |
| 555 |
|
| 556 |
my $align = $ffi->alignof($type); |
| 557 |
|
| 558 |
Returns the alignment of the given type in bytes. |
| 559 |
|
| 560 |
kindof |
| 561 |
|
| 562 |
[version 1.24] |
| 563 |
|
| 564 |
my $kind = $ffi->kindof($type); |
| 565 |
|
| 566 |
Returns the kind of a type. This is a string with a value of one of |
| 567 |
|
| 568 |
void |
| 569 |
|
| 570 |
scalar |
| 571 |
|
| 572 |
string |
| 573 |
|
| 574 |
closure |
| 575 |
|
| 576 |
record |
| 577 |
|
| 578 |
record-value |
| 579 |
|
| 580 |
pointer |
| 581 |
|
| 582 |
array |
| 583 |
|
| 584 |
object |
| 585 |
|
| 586 |
countof |
| 587 |
|
| 588 |
[version 1.24] |
| 589 |
|
| 590 |
my $count = $ffi->countof($type); |
| 591 |
|
| 592 |
For array types returns the number of elements in the array (returns 0 |
| 593 |
for variable length array). For the void type returns 0. Returns 1 for |
| 594 |
all other types. |
| 595 |
|
| 596 |
def |
| 597 |
|
| 598 |
[version 1.24] |
| 599 |
|
| 600 |
$ffi->def($package, $type, $value); |
| 601 |
my $value = $ff->def($package, $type); |
| 602 |
|
| 603 |
This method allows you to store data for types. If the $package is not |
| 604 |
provided, then the caller's package will be used. $type must be a legal |
| 605 |
Platypus type for the FFI::Platypus instance. |
| 606 |
|
| 607 |
unitof |
| 608 |
|
| 609 |
[version 1.24] |
| 610 |
|
| 611 |
my $unittype = $ffi->unitof($type); |
| 612 |
|
| 613 |
For array and pointer types, returns the basic type without the array |
| 614 |
or pointer part. In other words, for sin16[] or sint16* it will return |
| 615 |
sint16. |
| 616 |
|
| 617 |
find_lib |
| 618 |
|
| 619 |
[version 0.20] |
| 620 |
|
| 621 |
$ffi->find_lib( lib => $libname ); |
| 622 |
|
| 623 |
This is just a shortcut for calling FFI::CheckLib#find_lib and updating |
| 624 |
the "lib" attribute appropriately. Care should be taken though, as this |
| 625 |
method simply passes its arguments to FFI::CheckLib#find_lib, so if |
| 626 |
your module or script is depending on a specific feature in |
| 627 |
FFI::CheckLib then make sure that you update your prerequisites |
| 628 |
appropriately. |
| 629 |
|
| 630 |
find_symbol |
| 631 |
|
| 632 |
my $address = $ffi->find_symbol($name); |
| 633 |
|
| 634 |
Return the address of the given symbol (usually function). |
| 635 |
|
| 636 |
bundle |
| 637 |
|
| 638 |
[version 0.96 api = 1+] |
| 639 |
|
| 640 |
$ffi->bundle($package, \@args); |
| 641 |
$ffi->bundle(\@args); |
| 642 |
$ffi->bundle($package); |
| 643 |
$ffi->bundle; |
| 644 |
|
| 645 |
This is an interface for bundling compiled code with your distribution |
| 646 |
intended to eventually replace the package method documented above. See |
| 647 |
FFI::Platypus::Bundle for details on how this works. |
| 648 |
|
| 649 |
package |
| 650 |
|
| 651 |
[version 0.15 api = 0] |
| 652 |
|
| 653 |
$ffi->package($package, $file); # usually __PACKAGE__ and __FILE__ can be used |
| 654 |
$ffi->package; # autodetect |
| 655 |
|
| 656 |
Note: This method is officially discouraged in favor of bundle |
| 657 |
described above. |
| 658 |
|
| 659 |
If you use FFI::Build (or the older deprecated Module::Build::FFI to |
| 660 |
bundle C code with your distribution, you can use this method to tell |
| 661 |
the FFI::Platypus instance to look for symbols that came with the |
| 662 |
dynamic library that was built when your distribution was installed. |
| 663 |
|
| 664 |
abis |
| 665 |
|
| 666 |
my $href = $ffi->abis; |
| 667 |
my $href = FFI::Platypus->abis; |
| 668 |
|
| 669 |
Get the legal ABIs supported by your platform and underlying |
| 670 |
implementation. What is supported can vary a lot by CPU and by |
| 671 |
platform, or even between 32 and 64 bit on the same CPU and platform. |
| 672 |
They keys are the "ABI" names, also known as "calling conventions". The |
| 673 |
values are integers used internally by the implementation to represent |
| 674 |
those ABIs. |
| 675 |
|
| 676 |
abi |
| 677 |
|
| 678 |
$ffi->abi($name); |
| 679 |
|
| 680 |
Set the ABI or calling convention for use in subsequent calls to |
| 681 |
"function" or "attach". May be either a string name or integer value |
| 682 |
from the "abis" method above. |
| 683 |
|
| 684 |
EXAMPLES |
| 685 |
|
| 686 |
Here are some examples. These examples are provided in full with the |
| 687 |
Platypus distribution in the "examples" directory. There are also some |
| 688 |
more examples in FFI::Platypus::Type that are related to types. |
| 689 |
|
| 690 |
Passing and Returning Integers |
| 691 |
|
| 692 |
C Source |
| 693 |
|
| 694 |
int add(int a, int b) { |
| 695 |
return a+b; |
| 696 |
} |
| 697 |
|
| 698 |
Perl Source |
| 699 |
|
| 700 |
use FFI::Platypus 2.00; |
| 701 |
use FFI::CheckLib qw( find_lib_or_die ); |
| 702 |
use File::Basename qw( dirname ); |
| 703 |
|
| 704 |
my $ffi = FFI::Platypus->new( api => 2, lib => './add.so' ); |
| 705 |
$ffi->attach( add => ['int', 'int'] => 'int' ); |
| 706 |
|
| 707 |
print add(1,2), "\n"; # prints 3 |
| 708 |
|
| 709 |
Execute |
| 710 |
|
| 711 |
$ cc -shared -o add.so add.c |
| 712 |
$ perl add.pl |
| 713 |
3 |
| 714 |
|
| 715 |
Discussion |
| 716 |
|
| 717 |
Basic types like integers and floating points are the easiest to pass |
| 718 |
across the FFI boundary. Because they are values that are passed on the |
| 719 |
stack (or through registers) you don't need to worry about memory |
| 720 |
allocations or ownership. |
| 721 |
|
| 722 |
Here we are building our own C dynamic library using the native C |
| 723 |
compiler on a Unix like platform. The exact incantation that you will |
| 724 |
use to do this would unfortunately depend on your platform and C |
| 725 |
compiler. |
| 726 |
|
| 727 |
By default, Platypus uses the Platypus C language plugin, which gives |
| 728 |
you easy access to many of the basic types used by C APIs. (for example |
| 729 |
int, unsigned long, double, size_t and others). |
| 730 |
|
| 731 |
If you are working with another language like Fortran, Go, Rust or Zig, |
| 732 |
you will find similar examples where you can use the Platypus language |
| 733 |
plugin for that language and use the native types. |
| 734 |
|
| 735 |
String Arguments (with puts) |
| 736 |
|
| 737 |
C API |
| 738 |
|
| 739 |
cppreference - puts <https://en.cppreference.com/w/c/io/puts> |
| 740 |
|
| 741 |
Perl Source |
| 742 |
|
| 743 |
use FFI::Platypus 2.00; |
| 744 |
|
| 745 |
my $ffi = FFI::Platypus->new( api => 2, lib => undef ); |
| 746 |
$ffi->attach( puts => ['string'] => 'int' ); |
| 747 |
|
| 748 |
puts("hello world"); |
| 749 |
|
| 750 |
Execute |
| 751 |
|
| 752 |
$ perl puts.pl |
| 753 |
hello world |
| 754 |
|
| 755 |
Discussion |
| 756 |
|
| 757 |
Passing strings into a C function as an argument is also pretty easy |
| 758 |
using Platypus. Just use the string type, which is equivalent to the C |
| 759 |
<char *> or const char * types. |
| 760 |
|
| 761 |
In this example we are using the C Standard Library's puts function, so |
| 762 |
we don't need to build our own C code. We do still need to tell |
| 763 |
Platypus where to look for the puts symbol though, which is why we set |
| 764 |
lib to undef. This is a special value which tells Platypus to search |
| 765 |
the Perl runtime executable itself (including any dynamic libraries) |
| 766 |
for symbols. That helpfully includes the C Standard Library. |
| 767 |
|
| 768 |
Returning Strings |
| 769 |
|
| 770 |
C Source |
| 771 |
|
| 772 |
#include <string.h> |
| 773 |
#include <stdlib.h> |
| 774 |
|
| 775 |
const char * |
| 776 |
string_reverse(const char *input) |
| 777 |
{ |
| 778 |
static char *output = NULL; |
| 779 |
int i, len; |
| 780 |
|
| 781 |
if(output != NULL) |
| 782 |
free(output); |
| 783 |
|
| 784 |
if(input == NULL) |
| 785 |
return NULL; |
| 786 |
|
| 787 |
len = strlen(input); |
| 788 |
output = malloc(len+1); |
| 789 |
|
| 790 |
for(i=0; input[i]; i++) |
| 791 |
output[len-i-1] = input[i]; |
| 792 |
output[len] = '\0'; |
| 793 |
|
| 794 |
return output; |
| 795 |
} |
| 796 |
|
| 797 |
Perl Source |
| 798 |
|
| 799 |
use FFI::Platypus 2.00; |
| 800 |
|
| 801 |
my $ffi = FFI::Platypus->new( |
| 802 |
api => 2, |
| 803 |
lib => './string_reverse.so', |
| 804 |
); |
| 805 |
|
| 806 |
$ffi->attach( string_reverse => ['string'] => 'string' ); |
| 807 |
|
| 808 |
print string_reverse("\nHello world"); |
| 809 |
|
| 810 |
string_reverse(undef); |
| 811 |
|
| 812 |
Execute |
| 813 |
|
| 814 |
$ cc -shared -o string_reverse.so string_reverse.c |
| 815 |
$ perl string_reverse.pl |
| 816 |
dlrow olleH |
| 817 |
|
| 818 |
Discussion |
| 819 |
|
| 820 |
The C code here takes an input ASCII string and reverses it, returning |
| 821 |
the result. Note that it retains ownership of the string, the caller is |
| 822 |
expected to use it before the next call to reverse_string, or copy it. |
| 823 |
|
| 824 |
The Perl code simply declares the return value as string and is very |
| 825 |
simple. This does bring up an inconsistency though, strings passed in |
| 826 |
to a function as arguments are passed by reference, whereas the return |
| 827 |
value is copied! This is usually what you want because C APIs usually |
| 828 |
follow this pattern where you are expected to make your own copy of the |
| 829 |
string. |
| 830 |
|
| 831 |
At the end of the program we call reverse_string with undef, which gets |
| 832 |
translated to C as NULL. This allows it to free the output buffer so |
| 833 |
that the memory will not leak. |
| 834 |
|
| 835 |
Returning and Freeing Strings with Embedded NULLs |
| 836 |
|
| 837 |
C Source |
| 838 |
|
| 839 |
#include <string.h> |
| 840 |
#include <stdlib.h> |
| 841 |
|
| 842 |
char * |
| 843 |
string_crypt(const char *input, int len, const char *key) |
| 844 |
{ |
| 845 |
char *output; |
| 846 |
int i, n; |
| 847 |
|
| 848 |
if(input == NULL) |
| 849 |
return NULL; |
| 850 |
|
| 851 |
output = malloc(len+1); |
| 852 |
output[len] = '\0'; |
| 853 |
|
| 854 |
for(i=0, n=0; i<len; i++, n++) { |
| 855 |
if(key[n] == '\0') |
| 856 |
n = 0; |
| 857 |
output[i] = input[i] ^ key[n]; |
| 858 |
} |
| 859 |
|
| 860 |
return output; |
| 861 |
} |
| 862 |
|
| 863 |
void |
| 864 |
string_crypt_free(char *output) |
| 865 |
{ |
| 866 |
if(output != NULL) |
| 867 |
free(output); |
| 868 |
} |
| 869 |
|
| 870 |
Perl Source |
| 871 |
|
| 872 |
use FFI::Platypus 2.00; |
| 873 |
use FFI::Platypus::Buffer qw( buffer_to_scalar ); |
| 874 |
use YAML (); |
| 875 |
|
| 876 |
my $ffi = FFI::Platypus->new( |
| 877 |
api => 2, |
| 878 |
lib => './xor_cipher.so', |
| 879 |
); |
| 880 |
|
| 881 |
$ffi->attach( string_crypt_free => ['opaque'] ); |
| 882 |
|
| 883 |
$ffi->attach( string_crypt => ['string','int','string'] => 'opaque' => sub{ |
| 884 |
my($xsub, $input, $key) = @_; |
| 885 |
my $ptr = $xsub->($input, length($input), $key); |
| 886 |
my $output = buffer_to_scalar $ptr, length($input); |
| 887 |
string_crypt_free($ptr); |
| 888 |
return $output; |
| 889 |
}); |
| 890 |
|
| 891 |
my $orig = "hello world"; |
| 892 |
my $key = "foobar"; |
| 893 |
|
| 894 |
print YAML::Dump($orig); |
| 895 |
my $encrypted = string_crypt($orig, $key); |
| 896 |
print YAML::Dump($encrypted); |
| 897 |
my $decrypted = string_crypt($encrypted, $key); |
| 898 |
print YAML::Dump($decrypted); |
| 899 |
|
| 900 |
Execute |
| 901 |
|
| 902 |
$ cc -shared -o xor_cipher.so xor_cipher.c |
| 903 |
$ perl xor_cipher.pl |
| 904 |
--- hello world |
| 905 |
--- "\x0e\n\x03\x0e\x0eR\x11\0\x1d\x0e\x05" |
| 906 |
--- hello world |
| 907 |
|
| 908 |
Discussion |
| 909 |
|
| 910 |
The C code here also returns a string, but it has some different |
| 911 |
expectations, so we can't just use the string type like we did in the |
| 912 |
previous example and copy the string. |
| 913 |
|
| 914 |
This C code implements a simple XOR cipher. Given an input string and a |
| 915 |
key it returns an encrypted or decrypted output string where the |
| 916 |
characters are XORd with the key. There are some challenges here |
| 917 |
though. First the input and output strings can have embedded NULLs in |
| 918 |
them. For the string passed in, we can provide the length of the input |
| 919 |
string. For the output, the string type expects a NULL terminated |
| 920 |
string, so we can't use that. So instead we get a pointer to the output |
| 921 |
using the opaque type. Because we know that the output string is the |
| 922 |
same length as the input string we can convert the pointer to a regular |
| 923 |
Perl string using the buffer_to_scalar function. (For more details |
| 924 |
about working with buffers and strings see FFI::Platypus::Buffer). |
| 925 |
|
| 926 |
Next, the C code here does not keep the pointer to the output string, |
| 927 |
as in the previous example. We are expected to call string_encrypt_free |
| 928 |
when we are done. Since we are getting the pointer back from the C code |
| 929 |
instead of copying the string that is easy to do. |
| 930 |
|
| 931 |
Finally, we are using a wrapper to hide a lot of this complexity from |
| 932 |
our caller. The last argument to the attach call is a code reference |
| 933 |
which will wrap around the C function, which is passed in as the first |
| 934 |
argument of the wrapper. This is a good practice when writing modules, |
| 935 |
to hide the complexity of C. |
| 936 |
|
| 937 |
Pointers |
| 938 |
|
| 939 |
C Source |
| 940 |
|
| 941 |
void |
| 942 |
swap(int *a, int *b) |
| 943 |
{ |
| 944 |
int tmp = *b; |
| 945 |
*b = *a; |
| 946 |
*a = tmp; |
| 947 |
} |
| 948 |
|
| 949 |
Perl Source |
| 950 |
|
| 951 |
use FFI::Platypus 2.00; |
| 952 |
|
| 953 |
my $ffi = FFI::Platypus->new( |
| 954 |
api => 2, |
| 955 |
lib => './swap.so', |
| 956 |
); |
| 957 |
|
| 958 |
$ffi->attach( swap => ['int*','int*'] ); |
| 959 |
|
| 960 |
my $a = 1; |
| 961 |
my $b = 2; |
| 962 |
|
| 963 |
print "[a,b] = [$a,$b]\n"; |
| 964 |
|
| 965 |
swap( \$a, \$b ); |
| 966 |
|
| 967 |
print "[a,b] = [$a,$b]\n"; |
| 968 |
|
| 969 |
Execute |
| 970 |
|
| 971 |
$ cc -shared -o swap.so swap.c |
| 972 |
$ perl swap.pl |
| 973 |
[a,b] = [1,2] |
| 974 |
[a,b] = [2,1] |
| 975 |
|
| 976 |
Discussion |
| 977 |
|
| 978 |
Pointers are often use in C APIs to return simple values like this. |
| 979 |
Platypus provides access to pointers to primitive types by appending * |
| 980 |
to the primitive type. Here for example we are using int* to create a |
| 981 |
function that takes two pointers to integers and swaps their values. |
| 982 |
|
| 983 |
When calling the function from Perl we pass in a reference to a scalar. |
| 984 |
Strictly speaking Perl allows modifying the argument values to |
| 985 |
subroutines, so we could have allowed just passing in a scalar, but in |
| 986 |
the design of Platypus we decided that forcing the use of a reference |
| 987 |
here emphasizes that you are passing a reference to the variable, not |
| 988 |
just the value. |
| 989 |
|
| 990 |
Not pictured in this example, but you can also pass in undef for a |
| 991 |
pointer value and that will be translated into NULL on the C side. You |
| 992 |
can also return a pointer to a primitive type from a function, again |
| 993 |
this will be returned to Perl as a reference to a scalar. Platypus also |
| 994 |
supports string pointers (string*). (Though the C equivalent to a |
| 995 |
string* is a double pointer to char char**). |
| 996 |
|
| 997 |
Opaque Pointers (objects) |
| 998 |
|
| 999 |
C Source |
| 1000 |
|
| 1001 |
#include <string.h> |
| 1002 |
#include <stdlib.h> |
| 1003 |
|
| 1004 |
typedef struct person_t { |
| 1005 |
char *name; |
| 1006 |
unsigned int age; |
| 1007 |
} person_t; |
| 1008 |
|
| 1009 |
person_t * |
| 1010 |
person_new(const char *name, unsigned int age) { |
| 1011 |
person_t *self = malloc(sizeof(person_t)); |
| 1012 |
self->name = strdup(name); |
| 1013 |
self->age = age; |
| 1014 |
} |
| 1015 |
|
| 1016 |
const char * |
| 1017 |
person_name(person_t *self) { |
| 1018 |
return self->name; |
| 1019 |
} |
| 1020 |
|
| 1021 |
unsigned int |
| 1022 |
person_age(person_t *self) { |
| 1023 |
return self->age; |
| 1024 |
} |
| 1025 |
|
| 1026 |
void |
| 1027 |
person_free(person_t *self) { |
| 1028 |
free(self->name); |
| 1029 |
free(self); |
| 1030 |
} |
| 1031 |
|
| 1032 |
Perl Source |
| 1033 |
|
| 1034 |
use FFI::Platypus 2.00; |
| 1035 |
|
| 1036 |
my $ffi = FFI::Platypus->new( |
| 1037 |
api => 2, |
| 1038 |
lib => './person.so', |
| 1039 |
); |
| 1040 |
|
| 1041 |
$ffi->type( 'opaque' => 'person_t' ); |
| 1042 |
|
| 1043 |
$ffi->attach( person_new => ['string','unsigned int'] => 'person_t' ); |
| 1044 |
$ffi->attach( person_name => ['person_t'] => 'string' ); |
| 1045 |
$ffi->attach( person_age => ['person_t'] => 'unsigned int' ); |
| 1046 |
$ffi->attach( person_free => ['person_t'] ); |
| 1047 |
|
| 1048 |
my $person = person_new( 'Roger Frooble Bits', 35 ); |
| 1049 |
|
| 1050 |
print "name = ", person_name($person), "\n"; |
| 1051 |
print "age = ", person_age($person), "\n"; |
| 1052 |
|
| 1053 |
person_free($person); |
| 1054 |
|
| 1055 |
Execute |
| 1056 |
|
| 1057 |
$ cc -shared -o person.so person.c |
| 1058 |
$ perl person.pl |
| 1059 |
name = Roger Frooble Bits |
| 1060 |
age = 35 |
| 1061 |
|
| 1062 |
Discussion |
| 1063 |
|
| 1064 |
An opaque pointer is a pointer (memory address) that is pointing to |
| 1065 |
something but you do not know the structure of that something. In C |
| 1066 |
this is usually a void*, but it could also be a pointer to a struct |
| 1067 |
without a defined body. |
| 1068 |
|
| 1069 |
This is often used to as an abstraction around objects in C. Here in |
| 1070 |
the C code we have a person_t struct with functions to create (a |
| 1071 |
constructor), free (a destructor) and query it (methods). |
| 1072 |
|
| 1073 |
The Perl code can then use the constructor, methods and destructors |
| 1074 |
without having to understand the internals. The person_t internals can |
| 1075 |
also be changed without having to modify the calling code. |
| 1076 |
|
| 1077 |
We use the Platypus type method to create an alias of opaque called |
| 1078 |
person_t. While this is not necessary, it does make the Perl code |
| 1079 |
easier to understand. |
| 1080 |
|
| 1081 |
In later examples we will see how to hide the use of opaque types |
| 1082 |
further using the object type, but for some code direct use of opaque |
| 1083 |
is appropriate. |
| 1084 |
|
| 1085 |
Opaque Pointers (buffers and strings) |
| 1086 |
|
| 1087 |
C API |
| 1088 |
|
| 1089 |
cppreference - free <https://en.cppreference.com/w/c/memory/free> |
| 1090 |
|
| 1091 |
cppreference - malloc <https://en.cppreference.com/w/c/memory/malloc> |
| 1092 |
|
| 1093 |
cppreference - memcpy |
| 1094 |
<https://en.cppreference.com/w/c/string/byte/memcpy> |
| 1095 |
|
| 1096 |
cppreference - strdup |
| 1097 |
<https://en.cppreference.com/w/c/string/byte/strdup> |
| 1098 |
|
| 1099 |
Perl Source |
| 1100 |
|
| 1101 |
use FFI::Platypus 2.00; |
| 1102 |
use FFI::Platypus::Memory qw( malloc free memcpy strdup ); |
| 1103 |
|
| 1104 |
my $ffi = FFI::Platypus->new( api => 2 ); |
| 1105 |
my $buffer = malloc 14; |
| 1106 |
my $ptr_string = strdup("hello there!!\n"); |
| 1107 |
|
| 1108 |
memcpy $buffer, $ptr_string, 15; |
| 1109 |
|
| 1110 |
print $ffi->cast('opaque' => 'string', $buffer); |
| 1111 |
|
| 1112 |
free $ptr_string; |
| 1113 |
free $buffer; |
| 1114 |
|
| 1115 |
Execute |
| 1116 |
|
| 1117 |
$ perl malloc.pl |
| 1118 |
hello there!! |
| 1119 |
|
| 1120 |
Discussion |
| 1121 |
|
| 1122 |
Another useful application of the opaque type is for dealing with |
| 1123 |
buffers, and C strings that you do not immediately need to convert into |
| 1124 |
Perl strings. This example is completely contrived, but we are using |
| 1125 |
malloc to create a buffer of 14 bytes. We create a C string using |
| 1126 |
strdup, and then copy it into the buffer using memcpy. When we are done |
| 1127 |
with the opaque pointers we can free them using free since they. (This |
| 1128 |
is generally only okay when freeing memory that was allocated by |
| 1129 |
malloc, which is the case for strdup). |
| 1130 |
|
| 1131 |
These memory tools, along with others are provided by the |
| 1132 |
FFI::Platypus::Memory module, which is worth reviewing when you need to |
| 1133 |
manipulate memory from Perl when writing your FFI code. |
| 1134 |
|
| 1135 |
Just to verify that the memcpy did the right thing we convert the |
| 1136 |
buffer into a Perl string and print it out using the Platypus cast |
| 1137 |
method. |
| 1138 |
|
| 1139 |
Arrays |
| 1140 |
|
| 1141 |
C Source |
| 1142 |
|
| 1143 |
void |
| 1144 |
array_reverse(int a[], int len) { |
| 1145 |
int tmp, i; |
| 1146 |
|
| 1147 |
for(i=0; i < len/2; i++) { |
| 1148 |
tmp = a[i]; |
| 1149 |
a[i] = a[len-i-1]; |
| 1150 |
a[len-i-1] = tmp; |
| 1151 |
} |
| 1152 |
} |
| 1153 |
|
| 1154 |
void |
| 1155 |
array_reverse10(int a[10]) { |
| 1156 |
array_reverse(a, 10); |
| 1157 |
} |
| 1158 |
|
| 1159 |
Perl Source |
| 1160 |
|
| 1161 |
use FFI::Platypus 2.00; |
| 1162 |
|
| 1163 |
my $ffi = FFI::Platypus->new( |
| 1164 |
api => 2, |
| 1165 |
lib => './array_reverse.so', |
| 1166 |
); |
| 1167 |
|
| 1168 |
$ffi->attach( array_reverse => ['int[]','int'] ); |
| 1169 |
$ffi->attach( array_reverse10 => ['int[10]'] ); |
| 1170 |
|
| 1171 |
my @a = (1..10); |
| 1172 |
array_reverse10( \@a ); |
| 1173 |
print "$_ " for @a; |
| 1174 |
print "\n"; |
| 1175 |
|
| 1176 |
@a = (1..20); |
| 1177 |
array_reverse( \@a, 20 ); |
| 1178 |
print "$_ " for @a; |
| 1179 |
print "\n"; |
| 1180 |
|
| 1181 |
Execute |
| 1182 |
|
| 1183 |
$ cc -shared -o array_reverse.so array_reverse.c |
| 1184 |
$ perl array_reverse.pl |
| 1185 |
10 9 8 7 6 5 4 3 2 1 |
| 1186 |
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 |
| 1187 |
|
| 1188 |
Discussion |
| 1189 |
|
| 1190 |
Arrays in C are passed as pointers, so the C code here reverses the |
| 1191 |
array in place, rather than returning it. Arrays can also be fixed or |
| 1192 |
variable length. If the array is variable length the length of the |
| 1193 |
array must be provided in some way. In this case we explicitly pass in |
| 1194 |
a length. Another way might be to end the array with 0, if you don't |
| 1195 |
otherwise expect any 0 to appear in your data. For this reason, |
| 1196 |
Platypus adds a zero (or NULL in the case of pointers) element at the |
| 1197 |
end of the array when passing it into a variable length array type, |
| 1198 |
although we do not use it here. |
| 1199 |
|
| 1200 |
With Platypus you can declare an array type as being either fixed or |
| 1201 |
variable length. Because Perl stores arrays in completely differently |
| 1202 |
than C, a temporary array is created by Platypus, passed into the C |
| 1203 |
function as a pointer. When the function returns the array is re-read |
| 1204 |
by Platypus and the Perl array is updated with the new values. The |
| 1205 |
temporary array is then freed. |
| 1206 |
|
| 1207 |
You can use any primitive type for arrays, even string. You can also |
| 1208 |
return an array from a function. As in our discussion about strings, |
| 1209 |
when you return an array the value is copied, which is usually what you |
| 1210 |
want. |
| 1211 |
|
| 1212 |
Pointers as Arrays |
| 1213 |
|
| 1214 |
C Source |
| 1215 |
|
| 1216 |
#include <stdlib.h> |
| 1217 |
|
| 1218 |
int |
| 1219 |
array_sum(const int *a) { |
| 1220 |
int i, sum; |
| 1221 |
if(a == NULL) |
| 1222 |
return -1; |
| 1223 |
for(i=0, sum=0; a[i] != 0; i++) |
| 1224 |
sum += a[i]; |
| 1225 |
return sum; |
| 1226 |
} |
| 1227 |
|
| 1228 |
Perl Source |
| 1229 |
|
| 1230 |
use FFI::Platypus 2.00; |
| 1231 |
|
| 1232 |
my $ffi = FFI::Platypus->new( |
| 1233 |
api => 2, |
| 1234 |
lib => './array_sum.so', |
| 1235 |
); |
| 1236 |
|
| 1237 |
$ffi->attach( array_sum => ['int*'] => 'int' ); |
| 1238 |
|
| 1239 |
print array_sum(undef), "\n"; # -1 |
| 1240 |
print array_sum([0]), "\n"; # 0 |
| 1241 |
print array_sum([1,2,3,0]), "\n"; # 6 |
| 1242 |
|
| 1243 |
Execute |
| 1244 |
|
| 1245 |
$ cc -shared -o array_sum.so array_sum.c |
| 1246 |
$ perl array_sum.pl |
| 1247 |
-1 |
| 1248 |
0 |
| 1249 |
6 |
| 1250 |
|
| 1251 |
Discussion |
| 1252 |
|
| 1253 |
Starting with the Platypus version 2 API, you can also pass an array |
| 1254 |
reference in to a pointer argument. |
| 1255 |
|
| 1256 |
In C pointer and array arguments are often used somewhat |
| 1257 |
interchangeably. In this example we have an array_sum function that |
| 1258 |
takes a zero terminated array of integers and computes the sum. If the |
| 1259 |
pointer to the array is zero (0) then we return -1 to indicate an |
| 1260 |
error. |
| 1261 |
|
| 1262 |
This is the main advantage from Perl for using pointer argument rather |
| 1263 |
than an array one: the array argument will not let you pass in undef / |
| 1264 |
NULL. |
| 1265 |
|
| 1266 |
Sending Strings to GUI on Unix with libnotify |
| 1267 |
|
| 1268 |
C API |
| 1269 |
|
| 1270 |
Libnotify Reference Manual |
| 1271 |
<https://developer-old.gnome.org/libnotify/unstable> |
| 1272 |
|
| 1273 |
Perl Source |
| 1274 |
|
| 1275 |
use FFI::CheckLib; |
| 1276 |
use FFI::Platypus 2.00; |
| 1277 |
|
| 1278 |
my $ffi = FFI::Platypus->new( |
| 1279 |
api => 2, |
| 1280 |
lib => find_lib_or_die(lib => 'notify'), |
| 1281 |
); |
| 1282 |
|
| 1283 |
$ffi->attach( notify_init => ['string'] ); |
| 1284 |
$ffi->attach( notify_uninit => [] ); |
| 1285 |
$ffi->attach( notify_notification_new => ['string', 'string', 'string'] => 'opaque' ); |
| 1286 |
$ffi->attach( notify_notification_show => ['opaque', 'opaque'] ); |
| 1287 |
|
| 1288 |
my $message = join "\n", |
| 1289 |
"Hello from Platypus!", |
| 1290 |
"Welcome to the fun", |
| 1291 |
"world of FFI"; |
| 1292 |
|
| 1293 |
notify_init('Platypus Hello'); |
| 1294 |
my $n = notify_notification_new('Platypus Hello World', $message, 'dialog-information'); |
| 1295 |
notify_notification_show($n, undef); |
| 1296 |
notify_uninit(); |
| 1297 |
|
| 1298 |
Execute |
| 1299 |
|
| 1300 |
$ perl notify.pl |
| 1301 |
|
| 1302 |
Discussion |
| 1303 |
|
| 1304 |
The GNOME project provides an API to send notifications to its desktop |
| 1305 |
environment. Nothing here is particularly new: all of the types and |
| 1306 |
techniques are ones that we have seen before, except we are using a |
| 1307 |
third party library, instead of using our own C code or the standard C |
| 1308 |
library functions. |
| 1309 |
|
| 1310 |
When using a third party library you have to know the name or location |
| 1311 |
of it, which is not typically portable, so here we use FFI::CheckLib's |
| 1312 |
find_lib_or_die function. If the library is not found the script will |
| 1313 |
die with a useful diagnostic. FFI::CheckLib has a number of useful |
| 1314 |
features and will integrate nicely with Alien::Build based Aliens. |
| 1315 |
|
| 1316 |
The Win32 API with MessageBoxW |
| 1317 |
|
| 1318 |
Win32 API |
| 1319 |
|
| 1320 |
MessageBoxW function (winuser.h) |
| 1321 |
<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messageboxw> |
| 1322 |
|
| 1323 |
Perl Source |
| 1324 |
|
| 1325 |
use utf8; |
| 1326 |
use FFI::Platypus 2.00; |
| 1327 |
|
| 1328 |
my $ffi = FFI::Platypus->new( |
| 1329 |
api => 2, |
| 1330 |
lib => [undef], |
| 1331 |
); |
| 1332 |
|
| 1333 |
# see FFI::Platypus::Lang::Win32 |
| 1334 |
$ffi->lang('Win32'); |
| 1335 |
|
| 1336 |
# Send a Unicode string to the Windows API MessageBoxW function. |
| 1337 |
use constant MB_OK => 0x00000000; |
| 1338 |
use constant MB_DEFAULT_DESKTOP_ONLY => 0x00020000; |
| 1339 |
$ffi->attach( [MessageBoxW => 'MessageBox'] => [ 'HWND', 'LPCWSTR', 'LPCWSTR', 'UINT'] => 'int' ); |
| 1340 |
MessageBox(undef, "I ❤️ Platypus", "Confession", MB_OK|MB_DEFAULT_DESKTOP_ONLY); |
| 1341 |
|
| 1342 |
Execute |
| 1343 |
|
| 1344 |
$ perl win32_messagebox.pl |
| 1345 |
|
| 1346 |
Discussion |
| 1347 |
|
| 1348 |
The API used by Microsoft Windows presents some unique challenges. On |
| 1349 |
32 bit systems a different ABI is used than what is used by the |
| 1350 |
standard C library. It also provides a rats nest of type aliases. |
| 1351 |
Finally if you want to talk Unicode to any of the Windows API you will |
| 1352 |
need to use UTF-16LE instead of UTF-8 which is native to Perl. (The |
| 1353 |
Win32 API refers to these as LPWSTR and LPCWSTR types). As much as |
| 1354 |
possible the Win32 "language" plugin attempts to handle these |
| 1355 |
challenges transparently. For more details see |
| 1356 |
FFI::Platypus::Lang::Win32. |
| 1357 |
|
| 1358 |
Discussion |
| 1359 |
|
| 1360 |
The libnotify library is a desktop GUI notification system for the |
| 1361 |
GNOME Desktop environment. This script sends a notification event that |
| 1362 |
should show up as a balloon, for me it did so in the upper right hand |
| 1363 |
corner of my screen. |
| 1364 |
|
| 1365 |
Structured Data Records (by pointer or by reference) |
| 1366 |
|
| 1367 |
C API |
| 1368 |
|
| 1369 |
cppreference - localtime |
| 1370 |
<https://en.cppreference.com/w/c/chrono/localtime> |
| 1371 |
|
| 1372 |
Perl Source |
| 1373 |
|
| 1374 |
use FFI::Platypus 2.00; |
| 1375 |
use FFI::C; |
| 1376 |
|
| 1377 |
my $ffi = FFI::Platypus->new( |
| 1378 |
api => 2, |
| 1379 |
lib => [undef], |
| 1380 |
); |
| 1381 |
FFI::C->ffi($ffi); |
| 1382 |
|
| 1383 |
package Unix::TimeStruct { |
| 1384 |
|
| 1385 |
FFI::C->struct(tm => [ |
| 1386 |
tm_sec => 'int', |
| 1387 |
tm_min => 'int', |
| 1388 |
tm_hour => 'int', |
| 1389 |
tm_mday => 'int', |
| 1390 |
tm_mon => 'int', |
| 1391 |
tm_year => 'int', |
| 1392 |
tm_wday => 'int', |
| 1393 |
tm_yday => 'int', |
| 1394 |
tm_isdst => 'int', |
| 1395 |
tm_gmtoff => 'long', |
| 1396 |
_tm_zone => 'opaque', |
| 1397 |
]); |
| 1398 |
|
| 1399 |
# For now 'string' is unsupported by FFI::C, but we |
| 1400 |
# can cast the time zone from an opaque pointer to |
| 1401 |
# string. |
| 1402 |
sub tm_zone { |
| 1403 |
my $self = shift; |
| 1404 |
$ffi->cast('opaque', 'string', $self->_tm_zone); |
| 1405 |
} |
| 1406 |
|
| 1407 |
# attach the C localtime function |
| 1408 |
$ffi->attach( localtime => ['time_t*'] => 'tm', sub { |
| 1409 |
my($inner, $class, $time) = @_; |
| 1410 |
$time = time unless defined $time; |
| 1411 |
$inner->(\$time); |
| 1412 |
}); |
| 1413 |
} |
| 1414 |
|
| 1415 |
# now we can actually use our Unix::TimeStruct class |
| 1416 |
my $time = Unix::TimeStruct->localtime; |
| 1417 |
printf "time is %d:%d:%d %s\n", |
| 1418 |
$time->tm_hour, |
| 1419 |
$time->tm_min, |
| 1420 |
$time->tm_sec, |
| 1421 |
$time->tm_zone; |
| 1422 |
|
| 1423 |
Execute |
| 1424 |
|
| 1425 |
$ perl time_struct.pl |
| 1426 |
time is 3:48:19 MDT |
| 1427 |
|
| 1428 |
Discussion |
| 1429 |
|
| 1430 |
C and other machine code languages frequently provide interfaces that |
| 1431 |
include structured data records (defined using the struct keyword in |
| 1432 |
C). Some libraries will provide an API which you are expected to read |
| 1433 |
or write before and/or after passing them along to the library. |
| 1434 |
|
| 1435 |
For C pointers to strict, union, nested struct and nested union |
| 1436 |
structures, the easiest interface to use is via FFI::C. If you are |
| 1437 |
working with a struct that must be passed by value (not pointers), then |
| 1438 |
you will want to use FFI::Platypus::Record class instead. We will |
| 1439 |
discuss an example of that next. |
| 1440 |
|
| 1441 |
The C localtime function takes a pointer to a C struct. We simply |
| 1442 |
define the members of the struct using the FFI::C struct method. |
| 1443 |
Because we used the ffi method to tell FFI::C to use our local instance |
| 1444 |
of FFI::Platypus it registers the tm type for us, and we can just start |
| 1445 |
using it as a return type! |
| 1446 |
|
| 1447 |
Structured Data Records (on stack or by value) |
| 1448 |
|
| 1449 |
C Source |
| 1450 |
|
| 1451 |
#include <stdint.h> |
| 1452 |
#include <string.h> |
| 1453 |
|
| 1454 |
typedef struct color_t { |
| 1455 |
char name[8]; |
| 1456 |
uint8_t red; |
| 1457 |
uint8_t green; |
| 1458 |
uint8_t blue; |
| 1459 |
} color_t; |
| 1460 |
|
| 1461 |
color_t |
| 1462 |
color_increase_red(color_t color, uint8_t amount) |
| 1463 |
{ |
| 1464 |
strcpy(color.name, "reddish"); |
| 1465 |
color.red += amount; |
| 1466 |
return color; |
| 1467 |
} |
| 1468 |
|
| 1469 |
Perl Source |
| 1470 |
|
| 1471 |
use FFI::Platypus 2.00; |
| 1472 |
|
| 1473 |
my $ffi = FFI::Platypus->new( |
| 1474 |
api => 2, |
| 1475 |
lib => './color.so' |
| 1476 |
); |
| 1477 |
|
| 1478 |
package Color { |
| 1479 |
|
| 1480 |
use FFI::Platypus::Record; |
| 1481 |
use overload |
| 1482 |
'""' => sub { shift->as_string }, |
| 1483 |
bool => sub { 1 }, fallback => 1; |
| 1484 |
|
| 1485 |
record_layout_1($ffi, |
| 1486 |
'string(8)' => 'name', qw( |
| 1487 |
uint8 red |
| 1488 |
uint8 green |
| 1489 |
uint8 blue |
| 1490 |
)); |
| 1491 |
|
| 1492 |
sub as_string { |
| 1493 |
my($self) = @_; |
| 1494 |
sprintf "%s: [red:%02x green:%02x blue:%02x]", |
| 1495 |
$self->name, $self->red, $self->green, $self->blue; |
| 1496 |
} |
| 1497 |
|
| 1498 |
} |
| 1499 |
|
| 1500 |
$ffi->type('record(Color)' => 'color_t'); |
| 1501 |
$ffi->attach( color_increase_red => ['color_t','uint8'] => 'color_t' ); |
| 1502 |
|
| 1503 |
my $gray = Color->new( |
| 1504 |
name => 'gray', |
| 1505 |
red => 0xDC, |
| 1506 |
green => 0xDC, |
| 1507 |
blue => 0xDC, |
| 1508 |
); |
| 1509 |
|
| 1510 |
my $slightly_red = color_increase_red($gray, 20); |
| 1511 |
|
| 1512 |
print "$gray\n"; |
| 1513 |
print "$slightly_red\n"; |
| 1514 |
|
| 1515 |
Execute |
| 1516 |
|
| 1517 |
$ cc -shared -o color.so color.c |
| 1518 |
$ perl color.pl |
| 1519 |
gray: [red:dc green:dc blue:dc] |
| 1520 |
reddish: [red:f0 green:dc blue:dc] |
| 1521 |
|
| 1522 |
Discussion |
| 1523 |
|
| 1524 |
In the C source of this example, we pass a C struct by value by copying |
| 1525 |
it onto the stack. On the Perl side we create a Color class using |
| 1526 |
FFI::Platypus::Record, which allows us to pass the structure the way |
| 1527 |
the C source wants us to. |
| 1528 |
|
| 1529 |
Generally you should only reach for FFI::Platypus::Record if you need |
| 1530 |
to pass small records on the stack like this. For more complicated |
| 1531 |
(including nested) data you want to use FFI::C using pointers. |
| 1532 |
|
| 1533 |
Avoiding Copy Using Memory Windows (with libzmq3) |
| 1534 |
|
| 1535 |
C API |
| 1536 |
|
| 1537 |
ØMQ/3.2.6 API Reference <http://api.zeromq.org/3-2:_start> |
| 1538 |
|
| 1539 |
Perl Source |
| 1540 |
|
| 1541 |
use constant ZMQ_IO_THREADS => 1; |
| 1542 |
use constant ZMQ_MAX_SOCKETS => 2; |
| 1543 |
use constant ZMQ_REQ => 3; |
| 1544 |
use constant ZMQ_REP => 4; |
| 1545 |
use FFI::CheckLib qw( find_lib_or_die ); |
| 1546 |
use FFI::Platypus 2.00; |
| 1547 |
use FFI::Platypus::Memory qw( malloc ); |
| 1548 |
use FFI::Platypus::Buffer qw( scalar_to_buffer window ); |
| 1549 |
|
| 1550 |
my $endpoint = "ipc://zmq-ffi-$$"; |
| 1551 |
my $ffi = FFI::Platypus->new( |
| 1552 |
api => 2, |
| 1553 |
lib => find_lib_or_die lib => 'zmq', |
| 1554 |
); |
| 1555 |
|
| 1556 |
$ffi->attach(zmq_version => ['int*', 'int*', 'int*'] => 'void'); |
| 1557 |
|
| 1558 |
my($major,$minor,$patch); |
| 1559 |
zmq_version(\$major, \$minor, \$patch); |
| 1560 |
print "libzmq version $major.$minor.$patch\n"; |
| 1561 |
die "this script only works with libzmq 3 or better" unless $major >= 3; |
| 1562 |
|
| 1563 |
$ffi->type('opaque' => 'zmq_context'); |
| 1564 |
$ffi->type('opaque' => 'zmq_socket'); |
| 1565 |
$ffi->type('opaque' => 'zmq_msg_t'); |
| 1566 |
$ffi->attach(zmq_ctx_new => [] => 'zmq_context'); |
| 1567 |
$ffi->attach(zmq_ctx_set => ['zmq_context', 'int', 'int'] => 'int'); |
| 1568 |
$ffi->attach(zmq_socket => ['zmq_context', 'int'] => 'zmq_socket'); |
| 1569 |
$ffi->attach(zmq_connect => ['opaque', 'string'] => 'int'); |
| 1570 |
$ffi->attach(zmq_bind => ['zmq_socket', 'string'] => 'int'); |
| 1571 |
$ffi->attach(zmq_send => ['zmq_socket', 'opaque', 'size_t', 'int'] => 'int'); |
| 1572 |
$ffi->attach(zmq_msg_init => ['zmq_msg_t'] => 'int'); |
| 1573 |
$ffi->attach(zmq_msg_recv => ['zmq_msg_t', 'zmq_socket', 'int'] => 'int'); |
| 1574 |
$ffi->attach(zmq_msg_data => ['zmq_msg_t'] => 'opaque'); |
| 1575 |
$ffi->attach(zmq_errno => [] => 'int'); |
| 1576 |
$ffi->attach(zmq_strerror => ['int'] => 'string'); |
| 1577 |
|
| 1578 |
my $context = zmq_ctx_new(); |
| 1579 |
zmq_ctx_set($context, ZMQ_IO_THREADS, 1); |
| 1580 |
|
| 1581 |
my $socket1 = zmq_socket($context, ZMQ_REQ); |
| 1582 |
zmq_connect($socket1, $endpoint); |
| 1583 |
|
| 1584 |
my $socket2 = zmq_socket($context, ZMQ_REP); |
| 1585 |
zmq_bind($socket2, $endpoint); |
| 1586 |
|
| 1587 |
{ # send |
| 1588 |
our $sent_message = "hello there"; |
| 1589 |
my($pointer, $size) = scalar_to_buffer $sent_message; |
| 1590 |
my $r = zmq_send($socket1, $pointer, $size, 0); |
| 1591 |
die zmq_strerror(zmq_errno()) if $r == -1; |
| 1592 |
} |
| 1593 |
|
| 1594 |
{ # recv |
| 1595 |
my $msg_ptr = malloc 100; |
| 1596 |
zmq_msg_init($msg_ptr); |
| 1597 |
my $size = zmq_msg_recv($msg_ptr, $socket2, 0); |
| 1598 |
die zmq_strerror(zmq_errno()) if $size == -1; |
| 1599 |
my $data_ptr = zmq_msg_data($msg_ptr); |
| 1600 |
window(my $recv_message, $data_ptr, $size); |
| 1601 |
print "recv_message = $recv_message\n"; |
| 1602 |
} |
| 1603 |
|
| 1604 |
Execute |
| 1605 |
|
| 1606 |
$ perl zmq3.pl |
| 1607 |
libzmq version 4.3.4 |
| 1608 |
recv_message = hello there |
| 1609 |
|
| 1610 |
Discussion |
| 1611 |
|
| 1612 |
ØMQ is a high-performance asynchronous messaging library. There are a |
| 1613 |
few things to note here. |
| 1614 |
|
| 1615 |
Firstly, sometimes there may be multiple versions of a library in the |
| 1616 |
wild and you may need to verify that the library on a system meets your |
| 1617 |
needs (alternatively you could support multiple versions and configure |
| 1618 |
your bindings dynamically). Here we use zmq_version to ask libzmq which |
| 1619 |
version it is. |
| 1620 |
|
| 1621 |
zmq_version returns the version number via three integer pointer |
| 1622 |
arguments, so we use the pointer to integer type: int *. In order to |
| 1623 |
pass pointer types, we pass a reference. In this case it is a reference |
| 1624 |
to an undefined value, because zmq_version will write into the pointers |
| 1625 |
the output values, but you can also pass in references to integers, |
| 1626 |
floating point values and opaque pointer types. When the function |
| 1627 |
returns the $major variable (and the others) has been updated and we |
| 1628 |
can use it to verify that it supports the API that we require. |
| 1629 |
|
| 1630 |
Finally we attach the necessary functions, send and receive a message. |
| 1631 |
When we receive we use the FFI::Platypus::Buffer function window |
| 1632 |
instead of buffer_to_scalar. They have a similar effect in that the |
| 1633 |
provide a scalar from a region of memory, but window doesn't have to |
| 1634 |
copy any data, so it is cheaper to call. The only downside is that a |
| 1635 |
windowed scalar like this is read-only. |
| 1636 |
|
| 1637 |
libarchive |
| 1638 |
|
| 1639 |
C Documentation |
| 1640 |
|
| 1641 |
https://www.libarchive.org/ |
| 1642 |
|
| 1643 |
Perl Source |
| 1644 |
|
| 1645 |
use FFI::Platypus 2.00; |
| 1646 |
use FFI::CheckLib qw( find_lib_or_die ); |
| 1647 |
|
| 1648 |
# This example uses FreeBSD's libarchive to list the contents of any |
| 1649 |
# archive format that it suppors. We've also filled out a part of |
| 1650 |
# the ArchiveWrite class that could be used for writing archive formats |
| 1651 |
# supported by libarchive |
| 1652 |
|
| 1653 |
my $ffi = FFI::Platypus->new( |
| 1654 |
api => 2, |
| 1655 |
lib => find_lib_or_die(lib => 'archive'), |
| 1656 |
); |
| 1657 |
$ffi->type('object(Archive)' => 'archive_t'); |
| 1658 |
$ffi->type('object(ArchiveRead)' => 'archive_read_t'); |
| 1659 |
$ffi->type('object(ArchiveWrite)' => 'archive_write_t'); |
| 1660 |
$ffi->type('object(ArchiveEntry)' => 'archive_entry_t'); |
| 1661 |
|
| 1662 |
package Archive { |
| 1663 |
# base class is "abstract" having no constructor or destructor |
| 1664 |
|
| 1665 |
$ffi->mangler(sub { |
| 1666 |
my($name) = @_; |
| 1667 |
"archive_$name"; |
| 1668 |
}); |
| 1669 |
$ffi->attach( error_string => ['archive_t'] => 'string' ); |
| 1670 |
} |
| 1671 |
|
| 1672 |
package ArchiveRead { |
| 1673 |
our @ISA = qw( Archive ); |
| 1674 |
|
| 1675 |
$ffi->mangler(sub { |
| 1676 |
my($name) = @_; |
| 1677 |
"archive_read_$name"; |
| 1678 |
}); |
| 1679 |
|
| 1680 |
$ffi->attach( new => ['string'] => 'archive_read_t' ); |
| 1681 |
$ffi->attach( [ free => 'DESTROY' ] => ['archive_t'] ); |
| 1682 |
$ffi->attach( support_filter_all => ['archive_t'] => 'int' ); |
| 1683 |
$ffi->attach( support_format_all => ['archive_t'] => 'int' ); |
| 1684 |
$ffi->attach( open_filename => ['archive_t','string','size_t'] => 'int' ); |
| 1685 |
$ffi->attach( next_header2 => ['archive_t', 'archive_entry_t' ] => 'int' ); |
| 1686 |
$ffi->attach( data_skip => ['archive_t'] => 'int' ); |
| 1687 |
# ... define additional read methods |
| 1688 |
} |
| 1689 |
|
| 1690 |
package ArchiveWrite { |
| 1691 |
|
| 1692 |
our @ISA = qw( Archive ); |
| 1693 |
|
| 1694 |
$ffi->mangler(sub { |
| 1695 |
my($name) = @_; |
| 1696 |
"archive_write_$name"; |
| 1697 |
}); |
| 1698 |
|
| 1699 |
$ffi->attach( new => ['string'] => 'archive_write_t' ); |
| 1700 |
$ffi->attach( [ free => 'DESTROY' ] => ['archive_write_t'] ); |
| 1701 |
# ... define additional write methods |
| 1702 |
} |
| 1703 |
|
| 1704 |
package ArchiveEntry { |
| 1705 |
|
| 1706 |
$ffi->mangler(sub { |
| 1707 |
my($name) = @_; |
| 1708 |
"archive_entry_$name"; |
| 1709 |
}); |
| 1710 |
|
| 1711 |
$ffi->attach( new => ['string'] => 'archive_entry_t' ); |
| 1712 |
$ffi->attach( [ free => 'DESTROY' ] => ['archive_entry_t'] ); |
| 1713 |
$ffi->attach( pathname => ['archive_entry_t'] => 'string' ); |
| 1714 |
# ... define additional entry methods |
| 1715 |
} |
| 1716 |
|
| 1717 |
use constant ARCHIVE_OK => 0; |
| 1718 |
|
| 1719 |
# this is a Perl version of the C code here: |
| 1720 |
# https://github.com/libarchive/libarchive/wiki/Examples#List_contents_of_Archive_stored_in_File |
| 1721 |
|
| 1722 |
my $archive_filename = shift @ARGV; |
| 1723 |
unless(defined $archive_filename) |
| 1724 |
{ |
| 1725 |
print "usage: $0 archive.tar\n"; |
| 1726 |
exit; |
| 1727 |
} |
| 1728 |
|
| 1729 |
my $archive = ArchiveRead->new; |
| 1730 |
$archive->support_filter_all; |
| 1731 |
$archive->support_format_all; |
| 1732 |
|
| 1733 |
my $r = $archive->open_filename($archive_filename, 1024); |
| 1734 |
die "error opening $archive_filename: ", $archive->error_string |
| 1735 |
unless $r == ARCHIVE_OK; |
| 1736 |
|
| 1737 |
my $entry = ArchiveEntry->new; |
| 1738 |
|
| 1739 |
while($archive->next_header2($entry) == ARCHIVE_OK) |
| 1740 |
{ |
| 1741 |
print $entry->pathname, "\n"; |
| 1742 |
$archive->data_skip; |
| 1743 |
} |
| 1744 |
|
| 1745 |
Execute |
| 1746 |
|
| 1747 |
$ perl archive_object.pl archive.tar |
| 1748 |
archive.pl |
| 1749 |
archive_object.pl |
| 1750 |
|
| 1751 |
Discussion |
| 1752 |
|
| 1753 |
libarchive is the implementation of tar for FreeBSD provided as a |
| 1754 |
library and available on a number of platforms. |
| 1755 |
|
| 1756 |
One interesting thing about libarchive is that it provides a kind of |
| 1757 |
object oriented interface via opaque pointers. This example creates an |
| 1758 |
abstract class Archive, and concrete classes ArchiveWrite, ArchiveRead |
| 1759 |
and ArchiveEntry. The concrete classes can even be inherited from and |
| 1760 |
extended just like any Perl classes because of the way the custom types |
| 1761 |
are implemented. We use Platypus's object type for this implementation, |
| 1762 |
which is a wrapper around an opaque (can also be an integer) type that |
| 1763 |
is blessed into a particular class. |
| 1764 |
|
| 1765 |
Another advanced feature of this example is that we define a mangler to |
| 1766 |
modify the symbol resolution for each class. This means we can do this |
| 1767 |
when we define a method for Archive: |
| 1768 |
|
| 1769 |
$ffi->attach( support_filter_all => ['archive_t'] => 'int' ); |
| 1770 |
|
| 1771 |
Rather than this: |
| 1772 |
|
| 1773 |
$ffi->attach( |
| 1774 |
[ archive_read_support_filter_all => 'support_read_filter_all' ] => |
| 1775 |
['archive_t'] => 'int' ); |
| 1776 |
); |
| 1777 |
|
| 1778 |
As nice as libarchive is, note that we have to shoehorn then |
| 1779 |
archive_free function name into the Perl convention of using DESTROY as |
| 1780 |
the destructor. We can easily do that for just this one function with: |
| 1781 |
|
| 1782 |
$ffi->attach( [ free => 'DESTROY' ] => ['archive_t'] ); |
| 1783 |
|
| 1784 |
The libarchive is a large library with hundreds of methods. For |
| 1785 |
comprehensive FFI bindings for libarchive see Archive::Libarchive. |
| 1786 |
|
| 1787 |
unix open |
| 1788 |
|
| 1789 |
C API |
| 1790 |
|
| 1791 |
Input-output system calls in C |
| 1792 |
<https://www.geeksforgeeks.org/input-output-system-calls-c-create-open-close-read-write/> |
| 1793 |
|
| 1794 |
Perl Source |
| 1795 |
|
| 1796 |
use FFI::Platypus 2.00; |
| 1797 |
|
| 1798 |
{ |
| 1799 |
package FD; |
| 1800 |
|
| 1801 |
use constant O_RDONLY => 0; |
| 1802 |
use constant O_WRONLY => 1; |
| 1803 |
use constant O_RDWR => 2; |
| 1804 |
|
| 1805 |
use constant IN => bless \do { my $in=0 }, __PACKAGE__; |
| 1806 |
use constant OUT => bless \do { my $out=1 }, __PACKAGE__; |
| 1807 |
use constant ERR => bless \do { my $err=2 }, __PACKAGE__; |
| 1808 |
|
| 1809 |
my $ffi = FFI::Platypus->new( api => 2, lib => [undef]); |
| 1810 |
|
| 1811 |
$ffi->type('object(FD,int)' => 'fd'); |
| 1812 |
|
| 1813 |
$ffi->attach( [ 'open' => 'new' ] => [ 'string', 'int', 'mode_t' ] => 'fd' => sub { |
| 1814 |
my($xsub, $class, $fn, @rest) = @_; |
| 1815 |
my $fd = $xsub->($fn, @rest); |
| 1816 |
die "error opening $fn $!" if $$fd == -1; |
| 1817 |
$fd; |
| 1818 |
}); |
| 1819 |
|
| 1820 |
$ffi->attach( write => ['fd', 'string', 'size_t' ] => 'ssize_t' ); |
| 1821 |
$ffi->attach( read => ['fd', 'string', 'size_t' ] => 'ssize_t' ); |
| 1822 |
$ffi->attach( close => ['fd'] => 'int' ); |
| 1823 |
} |
| 1824 |
|
| 1825 |
my $fd = FD->new("file_handle.txt", FD::O_RDONLY); |
| 1826 |
|
| 1827 |
my $buffer = "\0" x 10; |
| 1828 |
|
| 1829 |
while(my $br = $fd->read($buffer, 10)) |
| 1830 |
{ |
| 1831 |
FD::OUT->write($buffer, $br); |
| 1832 |
} |
| 1833 |
|
| 1834 |
$fd->close; |
| 1835 |
|
| 1836 |
Execute |
| 1837 |
|
| 1838 |
$ perl file_handle.pl |
| 1839 |
Hello World |
| 1840 |
|
| 1841 |
Discussion |
| 1842 |
|
| 1843 |
The Unix file system calls use an integer handle for each open file. We |
| 1844 |
can use the same object type that we used for libarchive above, except |
| 1845 |
we let platypus know that the underlying type is int instead of opaque |
| 1846 |
(the latter being the default for the object type). Mainly just for |
| 1847 |
demonstration since Perl has much better IO libraries, but now we have |
| 1848 |
an OO interface to the Unix IO functions. |
| 1849 |
|
| 1850 |
Varadic Functions (with libcurl) |
| 1851 |
|
| 1852 |
C API |
| 1853 |
|
| 1854 |
curl_easy_init <https://curl.se/libcurl/c/curl_easy_init.html> |
| 1855 |
|
| 1856 |
curl_easy_setopt <https://curl.se/libcurl/c/curl_easy_setopt.html> |
| 1857 |
|
| 1858 |
curl_easy_perform <https://curl.se/libcurl/c/curl_easy_perform.html> |
| 1859 |
|
| 1860 |
curl_easy_cleanup <https://curl.se/libcurl/c/curl_easy_cleanup.html> |
| 1861 |
|
| 1862 |
CURLOPT_URL <https://curl.se/libcurl/c/CURLOPT_URL.html> |
| 1863 |
|
| 1864 |
Perl Source |
| 1865 |
|
| 1866 |
use FFI::Platypus 2.00; |
| 1867 |
use FFI::CheckLib qw( find_lib_or_die ); |
| 1868 |
use constant CURLOPT_URL => 10002; |
| 1869 |
|
| 1870 |
my $ffi = FFI::Platypus->new( |
| 1871 |
api => 2, |
| 1872 |
lib => find_lib_or_die(lib => 'curl'), |
| 1873 |
); |
| 1874 |
|
| 1875 |
my $curl_handle = $ffi->function( 'curl_easy_init' => [] => 'opaque' ) |
| 1876 |
->call; |
| 1877 |
|
| 1878 |
$ffi->function( 'curl_easy_setopt' => ['opaque', 'enum' ] => ['string'] ) |
| 1879 |
->call($curl_handle, CURLOPT_URL, "https://pl.atypus.org" ); |
| 1880 |
|
| 1881 |
$ffi->function( 'curl_easy_perform' => ['opaque' ] => 'enum' ) |
| 1882 |
->call($curl_handle); |
| 1883 |
|
| 1884 |
$ffi->function( 'curl_easy_cleanup' => ['opaque' ] ) |
| 1885 |
->call($curl_handle); |
| 1886 |
|
| 1887 |
Execute |
| 1888 |
|
| 1889 |
$ perl curl.pl |
| 1890 |
<!doctype html> |
| 1891 |
<html lang="en"> |
| 1892 |
<head> |
| 1893 |
<meta charset="utf-8" /> |
| 1894 |
<title>pl.atypus.org - Home for the Perl Platypus Project</title> |
| 1895 |
... |
| 1896 |
|
| 1897 |
Discussion |
| 1898 |
|
| 1899 |
The libcurl <https://curl.se/> library makes extensive use of "varadic" |
| 1900 |
functions. |
| 1901 |
|
| 1902 |
The C programming language and ABI have the concept of "varadic" |
| 1903 |
functions that can take a variable number and variable type of |
| 1904 |
arguments. Assuming you have a libffi that supports it (and most modern |
| 1905 |
systems should), then you can create bindings to a varadic function by |
| 1906 |
providing two sets of array references, one for the fixed arguments |
| 1907 |
(for reasons, C varadic functions must have at least one) and one for |
| 1908 |
variable arguments. In this example we call curl_easy_setopt as a |
| 1909 |
varadic function. |
| 1910 |
|
| 1911 |
For functions that have a large or infinite number of possible |
| 1912 |
signatures it may be impracticable or impossible to attach them all. |
| 1913 |
You can instead do as we did in this example, create a function object |
| 1914 |
using the function method and call it immediately. This is not as |
| 1915 |
performant either when you create or call as using the attach method, |
| 1916 |
but in some cases the performance penalty may be worth it or |
| 1917 |
unavoidable. |
| 1918 |
|
| 1919 |
Callbacks (with libcurl) |
| 1920 |
|
| 1921 |
C API |
| 1922 |
|
| 1923 |
curl_easy_init <https://curl.se/libcurl/c/curl_easy_init.html> |
| 1924 |
|
| 1925 |
curl_easy_setopt <https://curl.se/libcurl/c/curl_easy_setopt.html> |
| 1926 |
|
| 1927 |
curl_easy_perform <https://curl.se/libcurl/c/curl_easy_perform.html> |
| 1928 |
|
| 1929 |
curl_easy_cleanup <https://curl.se/libcurl/c/curl_easy_cleanup.html> |
| 1930 |
|
| 1931 |
CURLOPT_URL <https://curl.se/libcurl/c/CURLOPT_URL.html> |
| 1932 |
|
| 1933 |
CURLOPT_WRITEFUNCTION |
| 1934 |
<https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html> |
| 1935 |
|
| 1936 |
Perl Source |
| 1937 |
|
| 1938 |
use FFI::Platypus 2.00; |
| 1939 |
use FFI::CheckLib qw( find_lib_or_die ); |
| 1940 |
use FFI::Platypus::Buffer qw( window ); |
| 1941 |
use constant CURLOPT_URL => 10002; |
| 1942 |
use constant CURLOPT_WRITEFUNCTION => 20011; |
| 1943 |
|
| 1944 |
my $ffi = FFI::Platypus->new( |
| 1945 |
api => 2, |
| 1946 |
lib => find_lib_or_die(lib => 'curl'), |
| 1947 |
); |
| 1948 |
|
| 1949 |
my $curl_handle = $ffi->function( 'curl_easy_init' => [] => 'opaque' ) |
| 1950 |
->call; |
| 1951 |
|
| 1952 |
$ffi->function( 'curl_easy_setopt' => [ 'opaque', 'enum' ] => ['string'] ) |
| 1953 |
->call($curl_handle, CURLOPT_URL, "https://pl.atypus.org" ); |
| 1954 |
|
| 1955 |
my $html; |
| 1956 |
|
| 1957 |
my $closure = $ffi->closure(sub { |
| 1958 |
my($ptr, $len, $num, $user) = @_; |
| 1959 |
window(my $buf, $ptr, $len*$num); |
| 1960 |
$html .= $buf; |
| 1961 |
return $len*$num; |
| 1962 |
}); |
| 1963 |
|
| 1964 |
$ffi->function( 'curl_easy_setopt' => [ 'opaque', 'enum' ] => ['(opaque,size_t,size_t,opaque)->size_t'] => 'enum' ) |
| 1965 |
->call($curl_handle, CURLOPT_WRITEFUNCTION, $closure); |
| 1966 |
|
| 1967 |
$ffi->function( 'curl_easy_perform' => [ 'opaque' ] => 'enum' ) |
| 1968 |
->call($curl_handle); |
| 1969 |
|
| 1970 |
$ffi->function( 'curl_easy_cleanup' => [ 'opaque' ] ) |
| 1971 |
->call($curl_handle); |
| 1972 |
|
| 1973 |
if($html =~ /<title>(.*?)<\/title>/) { |
| 1974 |
print "$1\n"; |
| 1975 |
} |
| 1976 |
|
| 1977 |
Execute |
| 1978 |
|
| 1979 |
$ perl curl_callback.pl |
| 1980 |
pl.atypus.org - Home for the Perl Platypus Project |
| 1981 |
|
| 1982 |
Discussion |
| 1983 |
|
| 1984 |
This example is similar to the previous one, except instead of letting |
| 1985 |
libcurl <https://curl.se> write the content body to STDOUT, we give it |
| 1986 |
a callback to send the data to instead. The closure method can be used |
| 1987 |
to create a callback function pointer that can be called from C. The |
| 1988 |
type for the callback is in the form |
| 1989 |
(arg_type,arg_type,etc)->return_type where the argument types are in |
| 1990 |
parentheticals with an arrow between the argument types and the return |
| 1991 |
type. |
| 1992 |
|
| 1993 |
Inside the closure or callback we use the window function from |
| 1994 |
FFI::Platypus::Buffer again to avoid an extra copy. We still have to |
| 1995 |
copy the buffer to append it to $hmtl but it is at least one less copy. |
| 1996 |
|
| 1997 |
bundle your own code |
| 1998 |
|
| 1999 |
C Source |
| 2000 |
|
| 2001 |
ffi/foo.c: |
| 2002 |
|
| 2003 |
#include <ffi_platypus_bundle.h> |
| 2004 |
#include <string.h> |
| 2005 |
|
| 2006 |
typedef struct { |
| 2007 |
char *name; |
| 2008 |
int value; |
| 2009 |
} foo_t; |
| 2010 |
|
| 2011 |
foo_t* |
| 2012 |
foo__new(const char *class_name, const char *name, int value) { |
| 2013 |
(void)class_name; |
| 2014 |
foo_t *self = malloc( sizeof( foo_t ) ); |
| 2015 |
self->name = strdup(name); |
| 2016 |
self->value = value; |
| 2017 |
return self; |
| 2018 |
} |
| 2019 |
|
| 2020 |
const char * |
| 2021 |
foo__name(foo_t *self) { |
| 2022 |
return self->name; |
| 2023 |
} |
| 2024 |
|
| 2025 |
int |
| 2026 |
foo__value(foo_t *self) { |
| 2027 |
return self->value; |
| 2028 |
} |
| 2029 |
|
| 2030 |
void |
| 2031 |
foo__DESTROY(foo_t *self) { |
| 2032 |
free(self->name); |
| 2033 |
free(self); |
| 2034 |
} |
| 2035 |
|
| 2036 |
Perl Source |
| 2037 |
|
| 2038 |
lib/Foo.pm: |
| 2039 |
|
| 2040 |
package Foo; |
| 2041 |
|
| 2042 |
use strict; |
| 2043 |
use warnings; |
| 2044 |
use FFI::Platypus 2.00; |
| 2045 |
|
| 2046 |
my $ffi = FFI::Platypus->new( api => 2 ); |
| 2047 |
|
| 2048 |
$ffi->type('object(Foo)' => 'foo_t'); |
| 2049 |
$ffi->mangler(sub { |
| 2050 |
my $name = shift; |
| 2051 |
$name =~ s/^/foo__/; |
| 2052 |
$name; |
| 2053 |
}); |
| 2054 |
|
| 2055 |
$ffi->bundle; |
| 2056 |
|
| 2057 |
$ffi->attach( new => [ 'string', 'string', 'int' ] => 'foo_t' ); |
| 2058 |
$ffi->attach( name => [ 'foo_t' ] => 'string' ); |
| 2059 |
$ffi->attach( value => [ 'foo_t' ] => 'int' ); |
| 2060 |
$ffi->attach( DESTROY => [ 'foo_t' ] => 'void' ); |
| 2061 |
|
| 2062 |
1; |
| 2063 |
|
| 2064 |
t/foo.t: |
| 2065 |
|
| 2066 |
use Test2::V0; |
| 2067 |
use Foo; |
| 2068 |
|
| 2069 |
my $foo = Foo->new("platypus", 10); |
| 2070 |
isa_ok $foo, 'Foo'; |
| 2071 |
is $foo->name, "platypus"; |
| 2072 |
is $foo->value, 10; |
| 2073 |
|
| 2074 |
done_testing; |
| 2075 |
|
| 2076 |
Makefile.PL: |
| 2077 |
|
| 2078 |
use ExtUtils::MakeMaker; |
| 2079 |
use FFI::Build::MM; |
| 2080 |
my $fbmm = FFI::Build::MM->new; |
| 2081 |
WriteMakefile( |
| 2082 |
$fbmm->mm_args( |
| 2083 |
NAME => 'Foo', |
| 2084 |
DISTNAME => 'Foo', |
| 2085 |
VERSION => '1.00', |
| 2086 |
# ... |
| 2087 |
) |
| 2088 |
); |
| 2089 |
|
| 2090 |
sub MY::postamble |
| 2091 |
{ |
| 2092 |
$fbmm->mm_postamble; |
| 2093 |
} |
| 2094 |
|
| 2095 |
Execute |
| 2096 |
|
| 2097 |
With prove: |
| 2098 |
|
| 2099 |
$ prove -lvm |
| 2100 |
t/foo.t .. |
| 2101 |
# Seeded srand with seed '20221105' from local date. |
| 2102 |
ok 1 - Foo=SCALAR->isa('Foo') |
| 2103 |
ok 2 |
| 2104 |
ok 3 |
| 2105 |
1..3 |
| 2106 |
ok |
| 2107 |
All tests successful. |
| 2108 |
Files=1, Tests=3, 0 wallclock secs ( 0.00 usr 0.00 sys + 0.10 cusr 0.00 csys = 0.10 CPU) |
| 2109 |
Result: PASS |
| 2110 |
|
| 2111 |
With ExtUtils::MakeMaker: |
| 2112 |
|
| 2113 |
$ perl Makefile.PL |
| 2114 |
Generating a Unix-style Makefile |
| 2115 |
Writing Makefile for Foo |
| 2116 |
Writing MYMETA.yml and MYMETA.json |
| 2117 |
$ make |
| 2118 |
cp lib/Foo.pm blib/lib/Foo.pm |
| 2119 |
"/home/ollisg/opt/perl/5.37.5/bin/perl5.37.5" -MFFI::Build::MM=cmd -e fbx_build |
| 2120 |
CC ffi/foo.c |
| 2121 |
LD blib/lib/auto/share/dist/Foo/lib/libFoo.so |
| 2122 |
$ make test |
| 2123 |
"/home/ollisg/opt/perl/5.37.5/bin/perl5.37.5" -MFFI::Build::MM=cmd -e fbx_build |
| 2124 |
"/home/ollisg/opt/perl/5.37.5/bin/perl5.37.5" -MFFI::Build::MM=cmd -e fbx_test |
| 2125 |
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, 'blib/lib', 'blib/arch')" t/*.t |
| 2126 |
t/foo.t .. ok |
| 2127 |
All tests successful. |
| 2128 |
Files=1, Tests=3, 1 wallclock secs ( 0.00 usr 0.00 sys + 0.03 cusr 0.00 csys = 0.03 CPU) |
| 2129 |
Result: PASS |
| 2130 |
|
| 2131 |
Discussion |
| 2132 |
|
| 2133 |
You can bundle your own C code with your Perl extension. There are a |
| 2134 |
number of reasons you might want to do this Sometimes you need to |
| 2135 |
optimize a tight loop for speed. Or you might need a little bit of glue |
| 2136 |
code for your bindings to a library that isn't inherently FFI friendly. |
| 2137 |
Either way what you want is the FFI::Build system on the install step |
| 2138 |
and the FFI::Platypus::Bundle interface on the runtime step. If you are |
| 2139 |
using Dist::Zilla for your distribution, you will also want to check |
| 2140 |
out the Dist::Zilla::Plugin::FFI::Build plugin to make this as painless |
| 2141 |
as possible. |
| 2142 |
|
| 2143 |
One of the nice things about the bundle interface is that it is smart |
| 2144 |
enough to work with either App::Prove or ExtUtils::MakeMaker. This |
| 2145 |
means, unlike XS, you do not need to explicitly compile your C code in |
| 2146 |
development mode, that will be done for you when you call $ffi->bundle |
| 2147 |
|
| 2148 |
FAQ |
| 2149 |
|
| 2150 |
How do I get constants defined as macros in C header files |
| 2151 |
|
| 2152 |
This turns out to be a challenge for any language calling into C, which |
| 2153 |
frequently uses #define macros to define constants like so: |
| 2154 |
|
| 2155 |
#define FOO_STATIC 1 |
| 2156 |
#define FOO_DYNAMIC 2 |
| 2157 |
#define FOO_OTHER 3 |
| 2158 |
|
| 2159 |
As macros are expanded and their definitions are thrown away by the C |
| 2160 |
pre-processor there isn't any way to get the name/value mappings from |
| 2161 |
the compiled dynamic library. |
| 2162 |
|
| 2163 |
You can manually create equivalent constants in your Perl source: |
| 2164 |
|
| 2165 |
use constant FOO_STATIC => 1; |
| 2166 |
use constant FOO_DYNAMIC => 2; |
| 2167 |
use constant FOO_OTHER => 3; |
| 2168 |
|
| 2169 |
If there are a lot of these types of constants you might want to |
| 2170 |
consider using a tool (Convert::Binary::C can do this) that can extract |
| 2171 |
the constants for you. |
| 2172 |
|
| 2173 |
See also the "Integer constants" example in FFI::Platypus::Type. |
| 2174 |
|
| 2175 |
You can also use the new Platypus bundle interface to define Perl |
| 2176 |
constants from C space. This is more reliable, but does require a |
| 2177 |
compiler at install time. It is recommended mainly for writing bindings |
| 2178 |
against libraries that have constants that can vary widely from |
| 2179 |
platform to platform. See FFI::Platypus::Constant for details. |
| 2180 |
|
| 2181 |
What about enums? |
| 2182 |
|
| 2183 |
The C enum types are integers. The underlying type is up to the |
| 2184 |
platform, so Platypus provides enum and senum types for unsigned and |
| 2185 |
singed enums respectively. At least some compilers treat signed and |
| 2186 |
unsigned enums as different types. The enum values are essentially the |
| 2187 |
same as macro constants described above from an FFI perspective. Thus |
| 2188 |
the process of defining enum values is identical to the process of |
| 2189 |
defining macro constants in Perl. |
| 2190 |
|
| 2191 |
For more details on enumerated types see "Enum types" in |
| 2192 |
FFI::Platypus::Type. |
| 2193 |
|
| 2194 |
There is also a type plugin (FFI::Platypus::Type::Enum) that can be |
| 2195 |
helpful in writing interfaces that use enums. |
| 2196 |
|
| 2197 |
Memory leaks |
| 2198 |
|
| 2199 |
There are a couple places where memory is allocated, but never |
| 2200 |
deallocated that may look like memory leaks by tools designed to find |
| 2201 |
memory leaks like valgrind. This memory is intended to be used for the |
| 2202 |
lifetime of the perl process so there normally this isn't a problem |
| 2203 |
unless you are embedding a Perl interpreter which doesn't closely match |
| 2204 |
the lifetime of your overall application. |
| 2205 |
|
| 2206 |
Specifically: |
| 2207 |
|
| 2208 |
type cache |
| 2209 |
|
| 2210 |
some types are cached and not freed. These are needed as long as |
| 2211 |
there are FFI functions that could be called. |
| 2212 |
|
| 2213 |
attached functions |
| 2214 |
|
| 2215 |
Attaching a function as an xsub will definitely allocate memory that |
| 2216 |
won't be freed because the xsub could be called at any time, |
| 2217 |
including in END blocks. |
| 2218 |
|
| 2219 |
The Platypus team plans on adding a hook to free some of this "leaked" |
| 2220 |
memory for use cases where Perl and Platypus are embedded in a larger |
| 2221 |
application where the lifetime of the Perl process is significantly |
| 2222 |
smaller than the overall lifetime of the whole process. |
| 2223 |
|
| 2224 |
I get seg faults on some platforms but not others with a library using |
| 2225 |
pthreads. |
| 2226 |
|
| 2227 |
On some platforms, Perl isn't linked with libpthreads if Perl threads |
| 2228 |
are not enabled. On some platforms this doesn't seem to matter, |
| 2229 |
libpthreads can be loaded at runtime without much ill-effect. (Linux |
| 2230 |
from my experience doesn't seem to mind one way or the other). Some |
| 2231 |
platforms are not happy about this, and about the only thing that you |
| 2232 |
can do about it is to build Perl such that it links with libpthreads |
| 2233 |
even if it isn't a threaded Perl. |
| 2234 |
|
| 2235 |
This is not really an FFI issue, but a Perl issue, as you will have the |
| 2236 |
same problem writing XS code for the such libraries. |
| 2237 |
|
| 2238 |
Doesn't work on Perl 5.10.0. |
| 2239 |
|
| 2240 |
The first point release of Perl 5.10 was buggy, and is not supported by |
| 2241 |
Platypus. Please upgrade to a newer Perl. |
| 2242 |
|
| 2243 |
CAVEATS |
| 2244 |
|
| 2245 |
Platypus and Native Interfaces like libffi rely on the availability of |
| 2246 |
dynamic libraries. Things not supported include: |
| 2247 |
|
| 2248 |
Systems that lack dynamic library support |
| 2249 |
|
| 2250 |
Like MS-DOS |
| 2251 |
|
| 2252 |
Systems that are not supported by libffi |
| 2253 |
|
| 2254 |
Like OpenVMS |
| 2255 |
|
| 2256 |
Languages that do not support using dynamic libraries from other |
| 2257 |
languages |
| 2258 |
|
| 2259 |
This used to be the case with Google's Go, but is no longer the case. |
| 2260 |
This is a problem for C / XS code as well. |
| 2261 |
|
| 2262 |
Languages that do not compile to machine code |
| 2263 |
|
| 2264 |
Like .NET based languages and Java. |
| 2265 |
|
| 2266 |
The documentation has a bias toward using FFI / Platypus with C. This |
| 2267 |
is my fault, as my background mainly in C/C++ programmer (when I am not |
| 2268 |
writing Perl). In many places I use "C" as a short form for "any |
| 2269 |
language that can generate machine code and is callable from C". I |
| 2270 |
welcome pull requests to the Platypus core to address this issue. In an |
| 2271 |
attempt to ease usage of Platypus by non C programmers, I have written |
| 2272 |
a number of foreign language plugins for various popular languages (see |
| 2273 |
the SEE ALSO below). These plugins come with examples specific to those |
| 2274 |
languages, and documentation on common issues related to using those |
| 2275 |
languages with FFI. In most cases these are available for easy adoption |
| 2276 |
for those with the know-how or the willingness to learn. If your |
| 2277 |
language doesn't have a plugin YET, that is just because you haven't |
| 2278 |
written it yet. |
| 2279 |
|
| 2280 |
SUPPORT |
| 2281 |
|
| 2282 |
The intent of the FFI-Platypus team is to support the same versions of |
| 2283 |
Perl that are supported by the Perl toolchain. As of this writing that |
| 2284 |
means 5.16 and better. |
| 2285 |
|
| 2286 |
IRC: #native on irc.perl.org |
| 2287 |
|
| 2288 |
(click for instant chat room login) |
| 2289 |
<http://chat.mibbit.com/#[email protected]> |
| 2290 |
|
| 2291 |
If something does not work the way you think it should, or if you have |
| 2292 |
a feature request, please open an issue on this project's GitHub Issue |
| 2293 |
tracker: |
| 2294 |
|
| 2295 |
https://github.com/perlFFI/FFI-Platypus/issues |
| 2296 |
|
| 2297 |
CONTRIBUTING |
| 2298 |
|
| 2299 |
If you have implemented a new feature or fixed a bug then you may make |
| 2300 |
a pull request on this project's GitHub repository: |
| 2301 |
|
| 2302 |
https://github.com/PerlFFI/FFI-Platypus/pulls |
| 2303 |
|
| 2304 |
This project is developed using Dist::Zilla. The project's git |
| 2305 |
repository also comes with the Makefile.PL file necessary for building, |
| 2306 |
testing (and even installing if necessary) without Dist::Zilla. Please |
| 2307 |
keep in mind though that these files are generated so if changes need |
| 2308 |
to be made to those files they should be done through the project's |
| 2309 |
dist.ini file. If you do use Dist::Zilla and already have the necessary |
| 2310 |
plugins installed, then I encourage you to run dzil test before making |
| 2311 |
any pull requests. This is not a requirement, however, I am happy to |
| 2312 |
integrate especially smaller patches that need tweaking to fit the |
| 2313 |
project standards. I may push back and ask you to write a test case or |
| 2314 |
alter the formatting of a patch depending on the amount of time I have |
| 2315 |
and the amount of code that your patch touches. |
| 2316 |
|
| 2317 |
This project's GitHub issue tracker listed above is not Write-Only. If |
| 2318 |
you want to contribute then feel free to browse through the existing |
| 2319 |
issues and see if there is something you feel you might be good at and |
| 2320 |
take a whack at the problem. I frequently open issues myself that I |
| 2321 |
hope will be accomplished by someone in the future but do not have time |
| 2322 |
to immediately implement myself. |
| 2323 |
|
| 2324 |
Another good area to help out in is documentation. I try to make sure |
| 2325 |
that there is good document coverage, that is there should be |
| 2326 |
documentation describing all the public features and warnings about |
| 2327 |
common pitfalls, but an outsider's or alternate view point on such |
| 2328 |
things would be welcome; if you see something confusing or lacks |
| 2329 |
sufficient detail I encourage documentation only pull requests to |
| 2330 |
improve things. |
| 2331 |
|
| 2332 |
The Platypus distribution comes with a test library named libtest that |
| 2333 |
is normally automatically built by ./Build test. If you prefer to use |
| 2334 |
prove or run tests directly, you can use the ./Build libtest command to |
| 2335 |
build it. Example: |
| 2336 |
|
| 2337 |
% perl Makefile.PL |
| 2338 |
% make |
| 2339 |
% make ffi-test |
| 2340 |
% prove -bv t |
| 2341 |
# or an individual test |
| 2342 |
% perl -Mblib t/ffi_platypus_memory.t |
| 2343 |
|
| 2344 |
The build process also respects these environment variables: |
| 2345 |
|
| 2346 |
FFI_PLATYPUS_DEBUG_FAKE32 |
| 2347 |
|
| 2348 |
When building Platypus on 32 bit Perls, it will use the Math::Int64 C |
| 2349 |
API and make Math::Int64 a prerequisite. Setting this environment |
| 2350 |
variable will force Platypus to build with both of those options on a |
| 2351 |
64 bit Perl as well. |
| 2352 |
|
| 2353 |
% env FFI_PLATYPUS_DEBUG_FAKE32=1 perl Makefile.PL |
| 2354 |
DEBUG_FAKE32: |
| 2355 |
+ making Math::Int64 a prereq |
| 2356 |
+ Using Math::Int64's C API to manipulate 64 bit values |
| 2357 |
Generating a Unix-style Makefile |
| 2358 |
Writing Makefile for FFI::Platypus |
| 2359 |
Writing MYMETA.yml and MYMETA.json |
| 2360 |
% |
| 2361 |
|
| 2362 |
FFI_PLATYPUS_NO_ALLOCA |
| 2363 |
|
| 2364 |
Platypus uses the non-standard and somewhat controversial C function |
| 2365 |
alloca by default on platforms that support it. I believe that |
| 2366 |
Platypus uses it responsibly to allocate small amounts of memory for |
| 2367 |
argument type parameters, and does not use it to allocate large |
| 2368 |
structures like arrays or buffers. If you prefer not to use alloca |
| 2369 |
despite these precautions, then you can turn its use off by setting |
| 2370 |
this environment variable when you run Makefile.PL: |
| 2371 |
|
| 2372 |
helix% env FFI_PLATYPUS_NO_ALLOCA=1 perl Makefile.PL |
| 2373 |
NO_ALLOCA: |
| 2374 |
+ alloca() will not be used, even if your platform supports it. |
| 2375 |
Generating a Unix-style Makefile |
| 2376 |
Writing Makefile for FFI::Platypus |
| 2377 |
Writing MYMETA.yml and MYMETA.json |
| 2378 |
|
| 2379 |
V |
| 2380 |
|
| 2381 |
When building platypus may hide some of the excessive output when |
| 2382 |
probing and building, unless you set V to a true value. |
| 2383 |
|
| 2384 |
% env V=1 perl Makefile.PL |
| 2385 |
% make V=1 |
| 2386 |
... |
| 2387 |
|
| 2388 |
Coding Guidelines |
| 2389 |
|
| 2390 |
* Do not hesitate to make code contribution. Making useful |
| 2391 |
contributions is more important than following byzantine bureaucratic |
| 2392 |
coding regulations. We can always tweak things later. |
| 2393 |
|
| 2394 |
* Please make an effort to follow existing coding style when making |
| 2395 |
pull requests. |
| 2396 |
|
| 2397 |
* The intent of the FFI-Platypus team is to support the same versions |
| 2398 |
of Perl that are supported by the Perl toolchain. As of this writing |
| 2399 |
that means 5.16 and better. As such, please do not include any code |
| 2400 |
that requires a newer version of Perl. |
| 2401 |
|
| 2402 |
Performance Testing |
| 2403 |
|
| 2404 |
As Mark Twain was fond of saying there are four types of lies: lies, |
| 2405 |
damn lies, statistics and benchmarks. That being said, it can sometimes |
| 2406 |
be helpful to compare the runtime performance of Platypus if you are |
| 2407 |
making significant changes to the Platypus Core. For that I use |
| 2408 |
`FFI-Performance`, which can be found in my GitHub repository here: |
| 2409 |
|
| 2410 |
https://github.com/Perl5-FFI/FFI-Performance |
| 2411 |
|
| 2412 |
System integrators |
| 2413 |
|
| 2414 |
This distribution uses Alien::FFI in fallback mode, meaning if the |
| 2415 |
system doesn't provide pkg-config and libffi it will attempt to |
| 2416 |
download libffi and build it from source. If you are including Platypus |
| 2417 |
in a larger system (for example a Linux distribution) you only need to |
| 2418 |
make sure to declare pkg-config or pkgconf and the development package |
| 2419 |
for libffi as prereqs for this module. |
| 2420 |
|
| 2421 |
SEE ALSO |
| 2422 |
|
| 2423 |
Extending Platypus |
| 2424 |
|
| 2425 |
FFI::Platypus::Type |
| 2426 |
|
| 2427 |
Type definitions for Platypus. |
| 2428 |
|
| 2429 |
FFI::C |
| 2430 |
|
| 2431 |
Interface for defining structured data records for use with Platypus. |
| 2432 |
It supports C struct, union, nested structures and arrays of all of |
| 2433 |
those. It only supports passing these types by reference or pointer, |
| 2434 |
so if you need to pass structured data by value see |
| 2435 |
FFI::Platypus::Record below. |
| 2436 |
|
| 2437 |
FFI::Platypus::Record |
| 2438 |
|
| 2439 |
Interface for defining structured data records for use with Platypus. |
| 2440 |
Included in the Platypus core. Supports pass by value which is |
| 2441 |
uncommon in C, but frequently used in languages like Rust and Go. |
| 2442 |
Consider using FFI::C instead if you don't need to pass by value. |
| 2443 |
|
| 2444 |
FFI::Platypus::API |
| 2445 |
|
| 2446 |
The custom types API for Platypus. |
| 2447 |
|
| 2448 |
FFI::Platypus::Memory |
| 2449 |
|
| 2450 |
Memory functions for FFI. |
| 2451 |
|
| 2452 |
Languages |
| 2453 |
|
| 2454 |
FFI::Platypus::Lang::C |
| 2455 |
|
| 2456 |
Documentation and tools for using Platypus with the C programming |
| 2457 |
language |
| 2458 |
|
| 2459 |
FFI::Platypus::Lang::CPP |
| 2460 |
|
| 2461 |
Documentation and tools for using Platypus with the C++ programming |
| 2462 |
language |
| 2463 |
|
| 2464 |
FFI::Platypus::Lang::Fortran |
| 2465 |
|
| 2466 |
Documentation and tools for using Platypus with Fortran |
| 2467 |
|
| 2468 |
FFI::Platypus::Lang::Go |
| 2469 |
|
| 2470 |
Documentation and tools for using Platypus with Go |
| 2471 |
|
| 2472 |
FFI::Platypus::Lang::Pascal |
| 2473 |
|
| 2474 |
Documentation and tools for using Platypus with Free Pascal |
| 2475 |
|
| 2476 |
FFI::Platypus::Lang::Rust |
| 2477 |
|
| 2478 |
Documentation and tools for using Platypus with the Rust programming |
| 2479 |
language |
| 2480 |
|
| 2481 |
FFI::Platypus::Lang::ASM |
| 2482 |
|
| 2483 |
Documentation and tools for using Platypus with the Assembly |
| 2484 |
|
| 2485 |
FFI::Platypus::Lang::Win32 |
| 2486 |
|
| 2487 |
Documentation and tools for using Platypus with the Win32 API. |
| 2488 |
|
| 2489 |
FFI::Platypus::Lang::Zig |
| 2490 |
|
| 2491 |
Documentation and tools for using Platypus with the Zig programming |
| 2492 |
language |
| 2493 |
|
| 2494 |
Wasm and Wasm::Wasmtime |
| 2495 |
|
| 2496 |
Modules for writing WebAssembly bindings in Perl. This allows you to |
| 2497 |
call functions written in any language supported by WebAssembly. |
| 2498 |
These modules are also implemented using Platypus. |
| 2499 |
|
| 2500 |
Other Tools Related Tools Useful for FFI |
| 2501 |
|
| 2502 |
FFI::CheckLib |
| 2503 |
|
| 2504 |
Find dynamic libraries in a portable way. |
| 2505 |
|
| 2506 |
Convert::Binary::C |
| 2507 |
|
| 2508 |
A great interface for decoding C data structures, including structs, |
| 2509 |
enums, #defines and more. |
| 2510 |
|
| 2511 |
pack and unpack |
| 2512 |
|
| 2513 |
Native to Perl functions that can be used to decode C struct types. |
| 2514 |
|
| 2515 |
C::Scan |
| 2516 |
|
| 2517 |
This module can extract constants and other useful objects from C |
| 2518 |
header files that may be relevant to an FFI application. One downside |
| 2519 |
is that its use may require development packages to be installed. |
| 2520 |
|
| 2521 |
Other Foreign Function Interfaces |
| 2522 |
|
| 2523 |
Affix |
| 2524 |
|
| 2525 |
A wrapper around infix <https://github.com/sanko/infix>, an |
| 2526 |
FFI-focused just-in-time (JIT) compiler. |
| 2527 |
|
| 2528 |
NativeCall |
| 2529 |
|
| 2530 |
Promising interface to Platypus inspired by Raku. |
| 2531 |
|
| 2532 |
Win32::API |
| 2533 |
|
| 2534 |
Microsoft Windows specific FFI style interface. |
| 2535 |
|
| 2536 |
FFI |
| 2537 |
|
| 2538 |
Older, simpler, less featureful FFI. It used to be implemented using |
| 2539 |
FSF's ffcall. Because ffcall has been unsupported for some time, I |
| 2540 |
reimplemented this module using FFI::Platypus. |
| 2541 |
|
| 2542 |
C::DynaLib |
| 2543 |
|
| 2544 |
Another FFI for Perl that doesn't appear to have worked for a long |
| 2545 |
time. |
| 2546 |
|
| 2547 |
C::Blocks |
| 2548 |
|
| 2549 |
Embed a tiny C compiler into your Perl scripts. |
| 2550 |
|
| 2551 |
P5NCI |
| 2552 |
|
| 2553 |
Yet another FFI like interface that does not appear to be supported |
| 2554 |
or under development anymore. |
| 2555 |
|
| 2556 |
Other |
| 2557 |
|
| 2558 |
Alien::FFI |
| 2559 |
|
| 2560 |
Provides libffi for Platypus during its configuration and build |
| 2561 |
stages. |
| 2562 |
|
| 2563 |
ACKNOWLEDGMENTS |
| 2564 |
|
| 2565 |
In addition to the contributors mentioned below, I would like to |
| 2566 |
acknowledge Brock Wilcox (AWWAIID) and Meredith Howard (MHOWARD) whose |
| 2567 |
work on FFI::Sweet not only helped me get started with FFI but |
| 2568 |
significantly influenced the design of Platypus. |
| 2569 |
|
| 2570 |
Dan Book, who goes by Grinnz on IRC for answering user questions about |
| 2571 |
FFI and Platypus. |
| 2572 |
|
| 2573 |
In addition I'd like to thank Alessandro Ghedini (ALEXBIO) whose work |
| 2574 |
on another Perl FFI library helped drive some of the development ideas |
| 2575 |
for FFI::Platypus. |
| 2576 |
|
| 2577 |
AUTHOR |
| 2578 |
|
| 2579 |
Author: Graham Ollis <[email protected]> |
| 2580 |
|
| 2581 |
Contributors: |
| 2582 |
|
| 2583 |
Bakkiaraj Murugesan (bakkiaraj) |
| 2584 |
|
| 2585 |
Dylan Cali (calid) |
| 2586 |
|
| 2587 |
pipcet |
| 2588 |
|
| 2589 |
Zaki Mughal (zmughal) |
| 2590 |
|
| 2591 |
Fitz Elliott (felliott) |
| 2592 |
|
| 2593 |
Vickenty Fesunov (vyf) |
| 2594 |
|
| 2595 |
Gregor Herrmann (gregoa) |
| 2596 |
|
| 2597 |
Shlomi Fish (shlomif) |
| 2598 |
|
| 2599 |
Damyan Ivanov |
| 2600 |
|
| 2601 |
Ilya Pavlov (Ilya33) |
| 2602 |
|
| 2603 |
Petr Písař (ppisar) |
| 2604 |
|
| 2605 |
Mohammad S Anwar (MANWAR) |
| 2606 |
|
| 2607 |
Håkon Hægland (hakonhagland, HAKONH) |
| 2608 |
|
| 2609 |
Meredith (merrilymeredith, MHOWARD) |
| 2610 |
|
| 2611 |
Diab Jerius (DJERIUS) |
| 2612 |
|
| 2613 |
Eric Brine (IKEGAMI) |
| 2614 |
|
| 2615 |
szTheory |
| 2616 |
|
| 2617 |
José Joaquín Atria (JJATRIA) |
| 2618 |
|
| 2619 |
Pete Houston (openstrike, HOUSTON) |
| 2620 |
|
| 2621 |
Lukas Mai (MAUKE) |
| 2622 |
|
| 2623 |
COPYRIGHT AND LICENSE |
| 2624 |
|
| 2625 |
This software is copyright (c) 2015-2022 by Graham Ollis. |
| 2626 |
|
| 2627 |
This is free software; you can redistribute it and/or modify it under |
| 2628 |
the same terms as the Perl 5 programming language system itself. |
| 2629 |
|