PerlFFI/FFI-Platypus

Can you include your own C/C++ code and call a Perl sub with Platypus ?

ibrierley opened this issue · 2 comments

Hi, I'm just trying to understand a bit the possibilities with Platypus. I can see how to call existing libs, but are there any methods for calling Perl subs (from custom c/c++ code) with FFI?

I was looking at an example like the following......but could the "someFunc" function, somehow call a Perl method ? I'm probably looking for Perl Inline, but just trying to understand the strengths of both.

use FFI::TinyCC;
use FFI::Platypus;
 
my $ffi = FFI::Platypus->new( api => 1 );
my $tcc = FFI::TinyCC->new;
 
$tcc->compile_string(q{
  int
  someFunc(int a, int b)
  {
   // call some Perl sub to do something...
    return resultOfThatPerlSub;
  }
});
 
my $address = $tcc->get_symbol('someFunc');
 
$ffi->attach( [ $address => 'someFunc' ] => ['int','int'] => 'int' );
 
print someFunc(1,2), "\n";

Yes you can call Perl from C from Perl. What you are looking for is a closure, which lets you pass a code reference on the Perl side which comes through as a function pointer on the C/C++ side. That function pointer can be called from C to get you back into Perl. It is commonly useful for error handlers but can have other applications.

https://metacpan.org/pod/FFI::Platypus::Type#Closures
https://metacpan.org/pod/FFI::Platypus::Closure

Thanks, I will do some reading on those :).