| 1 | package Z3::FFI::ArrayType; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Carp qw/croak/; | ||
| 6 | |||
| 7 | use FFI::Platypus; | ||
| 8 | |||
| 9 | # ABSTRACT - Z3 Opaque array type creator | ||
| 10 | our $VERSION = '0.003'; | ||
| 11 | |||
| 12 | use constant _pointer_size => FFI::Platypus->new->sizeof('opaque'); | ||
| 13 | use constant _numeric_type => _pointer_size == 8 ? "Q" : "L"; | ||
| 14 | |||
| 15 | sub ffi_custom_type_api_1 { | ||
| 16 | # arg0 = class | ||
| 17 | # arg1 = FFI::Platypus instance | ||
| 18 | # arg2 = raw type name | ||
| 19 | my ($class, $ffi, $raw_type) = @_; | ||
| 20 | my $z3_class = "Z3::FFI::Types::$raw_type"; | ||
| 21 | |||
| 22 | my $config = {native_type => 'opaque'}; | ||
| 23 | |||
| 24 | # This gets used to track and preserve the perl side of things while we call the native side. | ||
| 25 | # Prevent the GC from destroying the values we point at. | ||
| 26 | my @stack; | ||
| 27 | |||
| 28 | $config->{perl_to_native_post} = sub { | ||
| 29 | pop @stack; | ||
| 30 | (); | ||
| 31 | }; | ||
| 32 | |||
| 33 | $config->{perl_to_native} = sub { | ||
| 34 | my $count = scalar @{$_[0]}; | ||
| 35 | |||
| 36 | for my $i (0..$count-1) { | ||
| 37 | croak "Array element $i is type ".ref($_[0][$i])." and not type $z3_class" unless ref($_[0][$i]) eq $z3_class; | ||
| 38 | } | ||
| 39 | |||
| 40 | my $pointers = pack((_numeric_type() x ($count+1)), (map {$$_} @{$_[0]}), 0); | ||
| 41 | my $array_pointer = unpack(_numeric_type(), pack('P', $pointers)); | ||
| 42 | # Save a reference to the pointer list, and the objects themselves so they don't get GC'd | ||
| 43 | push @stack, [ \$_[0], \$pointers ]; | ||
| 44 | return $array_pointer; | ||
| 45 | }; | ||
| 46 | |||
| 47 | $config->{native_to_perl} = sub { | ||
| 48 | ... # unimplemented, not needed. | ||
| 49 | }; | ||
| 50 | |||
| 51 | return $config; | ||
| 52 | } | ||
| 53 | |||
| 54 | 1; | ||
| 55 | |||
| 56 | __END__ |