【问题标题】:In Perl 6, how can I convert from raw bytes to floating point using the NativeCall interface?在 Perl 6 中,如何使用 NativeCall 接口将原始字节转换为浮点?
【发布时间】:2018-10-09 16:32:48
【问题描述】:

来自this conversation in the Perl 6 IRC channel 和Martin Barth 发布的一个问题,我正在尝试使用用于该目的的Perl6 NativeCall 接口reproduce this C code。这是我尝试过的:

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;

这会产生一个错误:

This type cannot unbox to a native integer: P6opaque, Any

我的解释是,你已经将它声明为一个整数,我不能把它变成原始内存,以便它可以从这里复制到那里。

这只是回答 Martin Barth 提出的更一般性问题的一种可能方式:如何将原始字节转换为浮点数。也许还有其他方法可以做到这一点,但无论如何我都很想知道如何将 C 程序转换为 NativeCall 等价物。

更新:与此同时,here's the original question this other post tries to be a solution for

【问题讨论】:

    标签: raku data-representation nativecall


    【解决方案1】:

    使用联合(所有字段共享相同的内存空间)可能是最自然的方式。像这样声明一个联合:

    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 中成为浮点数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-02
      • 2012-05-21
      • 1970-01-01
      • 2010-09-05
      相关资源
      最近更新 更多