handle_type#

Declare a Perl class for a C object type, with its destructor.

Synopsis#

Peta::FFI::handle_type("My::Schema", $lib, "schema_free");
my $compile = Peta::FFI::function($lib, "schema_compile", "(p)<My::Schema>");

my $schema = $compile->($schema_json) or die "invalid schema";
...                                   # schema_free runs when $schema goes

What it does#

After this, a signature may name the type as <My::Schema>:

  • As a result, the returned pointer becomes an object of class My::Schema; a NULL pointer becomes undef.

  • As an argument, a My::Schema object passes its pointer, and undef passes NULL. Anything else - another class’s handle, a plain number, a released handle - croaks rather than reaching C.

  • When the last reference to an object goes, the destructor is called with its pointer, exactly once. No DESTROY method is involved, so the class is free for the program’s own methods and subclasses.

$destructor is a function name in $lib, or an address. The library stays loaded for as long as the program runs, since objects may outlive every dlclose.

Edge cases#

  • Declared again with the same destructor - no effect.

  • Declared again with another destructor - croaks.