1. Perl
  2. Module
  3. here

FFI::Raw - Call C ++ functions directly from Perl

Perl provides XS language as a basic and general-purpose method for calling C language. increase.

But writing the XS language is a pain. It would be nice to be able to easily call a library written in C from Perl.

There is a mechanism to call a C language library called libffi from another language, and one of the Perl implementations of this is FFI::Raw. Easy to install from CPAN.

The example below is exactly what was written on the site, but is an example that calls a function called cos in a library called m .

use FFI::Raw;

my $cos = FFI::Raw->new(
  'libm.so', 'cos',
  # FFI::Raw::double, return value
  # FFI::Raw::double argument 1
);

print $cos->call(2.0);

The first argument is the dynamic library name. In C language, the file name corresponding to the dynamic library m is libm.so .

There is no description of the library search path in the documentation, but it seems that the ones in /lib and /usr/lib are the search targets.

There seems to be "how to set the environment variable LD_LIBRARY_PATH" and "how to add it to /etc/ld.so.conf" to add the search path of the library.

The second argument is the function name. The third argument is the return type, and the fourth and subsequent arguments are the argument types.

Other Perl FFI modules

Introducing other Perl FFI modules.

FFI::Platypus

There is FFI::Platypus as a Perl module of FFI. FFI::Platypus has a lot of FFI features and seems to be under continuous maintenance.

use FFI::Platypus 1.00;
 
# for all new code you should use api => 1
my $ffi = FFI::Platypus->new(api => 1);
$ffi->lib(undef); # search libc
 
# call dynamically
$ffi->function(puts => ['string'] =>'int')->call("hello world");
 
# attach as a xsub and call (much faster)
$ffi->attach(puts => ['string'] =>'int');
puts ("hello world");

Related Informatrion