【问题标题】:Does Perl 6 nativecast() to an object with repr('CPointer') DESTROY when GC'ed?Perl 6 nativecast() 在 GC 时是否会破坏带有 repr('CPointer') 的对象?
【发布时间】:2018-02-11 20:01:23
【问题描述】:
读取Basic use of Pointers 表示当NativeCall C 函数返回指向具有repr('CPointer') 类的对象的指针时,它将调用submethod DESTROY,我可以在其中放置我的函数以释放C 内存。 (顺便说一句,这是一个了不起的功能。)
如果我得到一个通用的Pointer,但后来决定将它nativecast() 传递给班级怎么办?垃圾收集时这是否也正确DESTROY()?我认为(并希望)它会,但我无法向自己证明这一点。
【问题讨论】:
标签:
casting
raku
nativecall
【解决方案1】:
鉴于以下测试用例的行为,我强烈怀疑它会:
use NativeCall;
my $done = False;
class Foo is repr<CPointer> {
method id { nativecast(Pointer[int32], self).deref }
# only log destrution of first object
submethod DESTROY {
if !$done {
$done = True;
say "first Foo with id {self.id} has died";
}
}
}
# avoid premature collection of buffers
my @keep-alive;
# allocate a bunch of buffers and cast them to Foo
# keep going until the garbage collector gets triggered
my $ = nativecast(Foo, @keep-alive.push(buf32.new($++)).tail)
while !$done;
当Foo 被回收时,将调用析构函数,即使上述Foo 是通过nativecast 创建的。如果您愿意,您可以在两者之间添加到 Pointer 的显式转换,但这不应该也没有任何区别。