代码之家  ›  专栏  ›  技术社区  ›  con

将C库函数与NativeCall合并到Perl6中

  •  3
  • con  · 技术社区  · 6 年前

    我想用 lgamma 从C的 math.h 在PARL6中。

    如何将其合并到Perl6中?

    我试过了

    use NativeCall;
    
    sub lgamma(num64 --> num64) is native(Str) {};
    
    say lgamma(3e0);
    
    my $x = 3.14;
    say lgamma($x);
    

    这适用于第一个数字(A Str )但第二次失败了, $x ,给出错误:

    This type cannot unbox to a native number: P6opaque, Rat
      in block <unit> at pvalue.p6 line 8
    

    我想做的非常简单,就像在Perl5中那样: use POSIX 'lgamma'; 然后 lgamma($x) 但在Perl6中我看不到如何做到这一点。

    2 回复  |  直到 6 年前
        1
  •  6
  •   Brad Gilbert    6 年前

    带有本机值的错误并不总是清晰的。

    基本上说老鼠不是数字。

    3.14 是一只老鼠。(理性)

    say 3.14.^name; # Rat
    say 3.14.nude.join('/'); # 157/50
    

    每次调用该值时,都可以将其强制为num。

    lgamma( $x.Num )
    

    看起来不太好。


    我将用另一个将所有实数强制为num的方法来包装本机Sub。
    (实数是除复数之外的所有数字)

    sub lgamma ( Num(Real) \n --> Num ){
      use NativeCall;
      sub lgamma (num64 --> num64) is native {}
    
      lgamma( n )
    }
    
    say lgamma(3);    # 0.6931471805599453
    say lgamma(3.14); # 0.8261387047770286
    
        2
  •  5
  •   jjmerelo    6 年前

    你的 $x 没有类型。如果你用任何类型的,就说 num64 它会说:

    Cannot assign a literal of type Rat (3.14) to a native variable of type num. You can declare the variable to be of type Real, or try to coerce the value with 3.14.Num or Num(3.14)
    

    所以你就这么做了:

    my  num64 $x = 3.14.Num;
    

    这会将数字精确地转换为 lgamma

    推荐文章