Permalink
Browse files

Add a way to name native routines

Sometimes the names used in a particular native library may not mesh
well with their usage in Perl. Rather than force our Perl subroutines to
have the same name as their native counterparts, we provide a way to
specify the name of the routine in the native library that our arbitrarily-
named Perl subroutine maps to.
  • Loading branch information...
1 parent 79429d9 commit eb3e3d88ef8419d7010d4f996add2858324dd618 @perlpilot perlpilot committed Aug 3, 2012
Showing with 27 additions and 1 deletion.
  1. +18 −0 README.markdown
  2. +9 −1 lib/NativeCall.pm6
View
@@ -33,6 +33,24 @@ that you can do is just adding to this simple pattern of declaring a Perl 6
sub, naming it after the symbol you want to call and marking it with the "native"
trait.
+## Changing names
+Sometimes you want the name of your Perl subroutine to be different from the name
+used in the library you're loading. Maybe the name is long or has different casing
+or is otherwise cumbersome within the context of the module you are trying to
+create.
+
+Zavolaj provides a "named" trait for you to specify the name of the native
+routine in your library that may be different from your Perl subroutine name.
+
+ module Foo;
+ use NativeCall;
+ our sub Init() is native('libfoo') is named('FOO_INIT') { * }
+
+Inside of "libfoo" there is a routine called "FOO\_INIT" but, since we're
+creating a module called Foo and we'd rather call the routine as Foo::Init,
+we use the "named" trait to specify the name of the symbol in "libfoo"
+and call the subroutine whatever we want ("Init" in this case).
+
## Passing and Returning Values
Normal Perl 6 signatures and the "returns" trait are used in order to convey
the type of arguments a native function expects and what it returns. Here is
View
@@ -97,6 +97,10 @@ multi sub map_return_type($type) {
$type
}
+my role Named[Str $name] {
+ method native_name() { $name }
+}
+
# This role is mixed in to any routine that is marked as being a
# native call.
my role Native[Routine $r, Str $libname] {
@@ -113,7 +117,7 @@ my role Native[Routine $r, Str $libname] {
"$libname$*VM<config><load_ext>";
nqp::buildnativecall(self,
nqp::unbox_s($realname), # library name
- nqp::unbox_s($r.name), # symbol to call
+ nqp::unbox_s(self.?native_name || $r.name), # symbol to call
nqp::unbox_s($conv), # calling convention
$arg_info,
return_hash_for($r.signature));
@@ -222,6 +226,10 @@ my class CArray is export is repr('CArray') {
}
}
+multi trait_mod:<is>(Routine $r, :$named!) is export {
+ $r does Named[$named];
+}
+
# Specifies that the routine is actually a native call, into the
# current executable (platform specific) or into a named library
multi trait_mod:<is>(Routine $r, :$native!) is export {

0 comments on commit eb3e3d8

Please sign in to comment.