Cur*_*mes 5 boxing perl6 nativecall
Perl 6 文档列出了一堆类型.其中一些(例如Str)具有更复杂的盒子/拆箱行为.
是否可以定义我自己的类型,为box/unboxing指定我自己的例程?对于一个特定的项目,我有一堆我正在重用的类型,并且基本上一遍又一遍地剪切/粘贴我的访问器功能.
例如,C Struct使用a time_t,我插入访问器方法来往/来自a DateTime.另一个例子是以逗号分隔的列表,我想进入/离开Array并自动处理split/ join.
有一个更好的方法吗?
编辑:添加示例:
constant time_t = uint64;
constant FooType_t = uint16;
enum FooType <A B C>;
class Foo is repr('CStruct') is rw
{
has uint32 $.id;
has Str $.name;
has FooType_t $.type;
has time_t $.time;
method name(Str $n?) {
$!name := $n with $n;
$!name;
}
method type(FooType $t?) {
$!type = $t with $t;
FooType($!type);
}
method time(DateTime $d?) {
$!time = .Instant.to-posix[0].Int with $d;
DateTime.new($!time)
}
}
my $f = Foo.new;
$f.id = 12;
$f.name('myname');
$f.type(B);
$f.time(DateTime.new('2000-01-01T12:34:56Z'));
say "$f.id() $f.name() $f.type() $f.time()";
# 12 myname B 2000-01-01T12:34:56Z
Run Code Online (Sandbox Code Playgroud)
这是有效的,我可以设置CStructPerl-ish方式的各个字段(没有左值,但我可以将它们作为参数传递).
现在我想用time_t,FooType_t等许多领域在许多结构中,让他们采取同样的方式.除了一遍又一遍地复制这些方法之外,还有更好的方法吗?
也许宏可以帮到这里?我还没有掌握它们.
您可以编写一个特征,在获取或存储属性时处理自动属性转换.以下内容可以帮助您入门:
multi sub trait_mod:<is>(Attribute:D $attr, :$autoconv!) {
use nqp;
my $name := $attr.name;
$attr.package.^add_method: $name.substr(2), do given $attr.type {
when .REPR eq 'P6int' {
method () is rw {
my $self := self;
Proxy.new:
FETCH => method () {
$autoconv.out(nqp::getattr_i($self, $self.WHAT, $name));
},
STORE => method ($_) {
nqp::bindattr_i($self, $self.WHAT, $name,
nqp::decont($autoconv.in($_)));
}
}
}
default {
die "FIXME: no idea how to handle {.^name}";
}
}
}
Run Code Online (Sandbox Code Playgroud)
例如,以您的用例为例time_t:
constant time_t = uint64;
class CTimeConversion {
multi method in(Int $_ --> time_t) { $_ }
multi method in(DateTime $_ --> time_t) { .posix }
method out(time_t $_ --> DateTime) { DateTime.new($_) }
}
class CTimeSpan is repr<CStruct> {
has time_t $.start is autoconv(CTimeConversion);
has time_t $.end is autoconv(CTimeConversion);
}
Run Code Online (Sandbox Code Playgroud)
最后,一些示例代码显示它的工作原理:
my $span = CTimeSpan.new;
say $span;
say $span.end;
$span.end = DateTime.now;
say $span;
say $span.end;
Run Code Online (Sandbox Code Playgroud)