# New Ticket Created by  Benjamin Goldberg 
# Please include the string:  [perl #131396]
# in the subject line of all future correspondence about this issue. 
# <URL: https://rt.perl.org/Ticket/Display.html?id=131396 >


The ‘is native’ trait works on methods.  It would be nice if this were 
documented.
Also, users can (and probably should) create their own traits which call
trait_mod:<is>(Routine, :$native);

If we start with the code in
https://perl6advent.wordpress.com/2015/12/21/day-21-nativecall-backs-and-beyond-c/
we can modify it as follows:

multi trait_mod:<is>(Routine $r, :$e!) {
    trait_mod:<is>($r, native => ‘expat’);
    trait_mod:<is>($r, symbol => ‘XML_’ ~ $name);
};
class XML_Parser is repr(‘CPointer’) {
     multi trait_mod:<is>(Routine $r, :$p!) {
        trait_mod:<is>($r, native => ‘expat’);
        trait_mod:<is>($r, symbol => ‘XML_Parser’ ~ $name);
    };

    method SetElemetHandler(
        &start (OpaquePointer, Str, CArray[Str]), &end (OpaquePointer, Str))
    ) {...} is e;
    our sub Create(Str -> XML_Parser) is p {...};
    method Free() is p {...};
    method Parse(Buf, int32, int32 --> int32) is e {...};
}

my $xml = ...;
my $parser = XML_Parser::Create('UTF-8');
$parser.SetElementHandler($parser, &start-element, &end-element);
my $buf = $xml.encode('UTF-8');
$parser.Parse($buf, $buf.elems, 1);
$parser.Free;

We could make the code even more compact, with the aid of a module to
generate 'e' and 'p' for us.
That module might be used as:
    use NativeCall::MakeTrait "e", native => "expat", prefix => 'XML_';
    use NativeCall::MakeTrait "p", native => "expat", prefix => 
'XML_Parser';
with details for that module left as an exercise for the reader :).

Reply via email to