From f2dd4669a2209c61ce2a2958fc0b50b832bdb280 Mon Sep 17 00:00:00 2001 From: Sanko Robinson Date: Mon, 23 Aug 2021 20:41:29 -0400 Subject: [PATCH] Lazy enum values by installing the CODE ref as required (PerlFFI/FFI-Platypus-Type-Enum#11) Issues: - Cannot cast value back to name (for return values from C, etc.) --- lib/FFI/Platypus/Type/Enum.pm | 3 ++- t/ffi_platypus_type_enum.t | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/FFI/Platypus/Type/Enum.pm b/lib/FFI/Platypus/Type/Enum.pm index 8bd86db..e58032f 100644 --- a/lib/FFI/Platypus/Type/Enum.pm +++ b/lib/FFI/Platypus/Type/Enum.pm @@ -335,7 +335,8 @@ sub ffi_custom_type_api_1 foreach my $name ($name,@aliases) { my $full = join '::', $package, $prefix . ( $config{casing} eq 'upper' ? uc($name) : $name ); - constant->import($full, $index); + no strict 'refs'; + ref $index eq 'CODE' ? *{$full} = $index : constant->import($full, $index); } } } diff --git a/t/ffi_platypus_type_enum.t b/t/ffi_platypus_type_enum.t index 93ab998..b9f40fe 100644 --- a/t/ffi_platypus_type_enum.t +++ b/t/ffi_platypus_type_enum.t @@ -238,4 +238,21 @@ subtest 'dualvar' => sub { }; +subtest 'code' => sub { + + my $ffi = FFI::Platypus->new( api => 1 ); + + $ffi->load_custom_type('::Enum', 'enum1', { package => 'Foo4', casing => 'keep' }, + 'zero', + 'one', + 'two', + 'three', + ['five' => sub () { Foo4::two() + Foo4::three() } ] + ); + + is($ffi->cast('enum', 'enum1', 2), 'two'); + todo '::Enum cannot back cast lazy values' => sub {is($ffi->cast('enum', 'enum1', 5), 'five')}; + is(Foo4::five(), 5); +}; + done_testing;