PerlFFI / FFI-Platypus

Write Perl bindings to non-Perl libraries with FFI. No XS required.
89 stars 23 forks source link

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

Closed ibrierley closed 3 years ago

ibrierley commented 3 years ago

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";
plicease commented 3 years ago

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

ibrierley commented 3 years ago

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