从this conversation in the Perl 6 IRC channel和Martin Barth发布的问题,我尝试reproduce this C code使用Perl6 NativeCall接口,该接口用于此目的。这就是我的尝试:
let myShifts = [Shifts]()
//populate your myShifts array.
func filteredShifts() -> [Shifts] {
var regions = Set<String>()
let filteredShifts = myShifts.filter {
if !regions.contains($0.region) {
regions.insert(aShift.region)
return true
} else { return false }
}
return filteredShifts
}
这会产生错误:
use NativeCall;
my uint32 $num = .new;
my num32 $float = .new: Num(1.0);
sub memcpy(num32 $float, uint32 $num, int32 $size) is native('Str') { * };
memcpy($float,$num,4);
say $num;
我将其解释为,您已将其声明为整数,我无法将其转换为原始内存,以便可以从此处复制到此处。
这只是回答Martin Barth更常见问题的一种可能方式:如何将原始字节转换为浮点数。也许有其他方法可以做到这一点,但无论如何我都很想知道如何将C程序转换成NativeCall等价物。
更新:与此同时,here's the original question this other post tries to be a solution for。
答案 0 :(得分:9)
使用union(所有字段共享相同的内存空间)可能是最自然的方式。声明这样的联盟:
my class Convertor is repr<CUnion> {
has uint32 $.i is rw;
has num32 $.n is rw;
}
然后用它来进行转换:
my $c = Convertor.new;
$c.i = 0b1000010111101101100110011001101;
say $c.n # 123.4000015258789
另一个与问题的内容无关的问题,但在发布的代码中出现:原生整数和数字时间从不需要对它们进行.new
,因为它们不是对象类型。这样:
my uint32 $num = .new;
应该是:
my uint32 $num;
和
my num32 $float = .new: Num(1.0);
应该是:
my num32 $float = 1e0;
使用e
指数是文字在Perl 6中浮动的原因。