NAME

FFI::C::Util - Utility functions for dealing with structured C data

VERSION

version 0.11

SYNOPSIS

 use FFI::C::Util qw( perl_to_c take );
 use FFI::C::StructDef;
 use FFI::Platypus::Memory qw( free );
 
 my $def = FFI::C::StructDef->new(
   members => [
     x => 'uint8',
     y => 'sint64',
   ],
 );
 my $inst = $def->create;
 
 # initalize members
 perl_to_c($inst, { x => 1, y => 2 });
 
 # take ownership
 my $ptr = take $inst;
 
 # since we took ownership, we are responsible for freeing the memory:
 free $ptr;

DESCRIPTION

This module provides some useful utility functions for dealing with the various def instances provided by FFI::C

FUNCTIONS

perl_to_c

 perl_to_c $instance, \%values;  # for Struct/Union
 perl_to_c $instance, \@values;  # for Array

This function initializes the members of an instance.

c_to_perl

 my $perl = c_to_perl $instance;

This function takes an instance and returns the nested members as Perl data structures.

owned

 my $bool = owned $instance;

Returns true of the $instance owns its allocated memory. That is, it will free up the allocated memory when it falls out of scope. Reasons an instance might not be owned are:

the instance is nested inside another object that owns the memory
the instance was returned from a C function that owns the memory
ownership was taken away by the take function below.

take

 my $ptr = take $instance;

This function takes ownership of the instance pointer, and returns the opaque pointer. This means a couple of things:

$instance will not free its data automatically

You should call free on it manually to free the memory it is using.

$instance cannot be used anymore

So don't try to get/set any of its members, or pass it into a function.

The returned pointer can be cast into something else or passed into a function that takes an opaque argument.

addressof

[version 0.11]

 my $ptr = addressof $instance;

This function returns the address (as an opaque type) of the instance object. This is similar to take above in that it gets you the address of the object, but doesn't take ownership of it, so care needs to be taken when using $ptr that the object is still allocated.

set_array_count

 set_array_count $inst, $count;

This function sets the element count on a variable array returned from C (where normally there is no way to know from just the return value). If you try to set a count on a non-array or a fixed sized array an exception will be thrown.

SEE ALSO

FFI::C
FFI::C::Array
FFI::C::ArrayDef
FFI::C::Def
FFI::C::File
FFI::C::PosixFile
FFI::C::Struct
FFI::C::StructDef
FFI::C::Union
FFI::C::UnionDef
FFI::C::Util
FFI::Platypus::Record

AUTHOR

Graham Ollis <plicease@cpan.org>

COPYRIGHT AND LICENSE

This software is copyright (c) 2020,2021 by Graham Ollis.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.