使用 NativeCall 将 C 库函数合并到 Perl6 中 [英] Incorporate C library function into Perl6 with NativeCall

查看:42
本文介绍了使用 NativeCall 将 C 库函数合并到 Perl6 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Perl6 中使用 C 的 math.h 中的 lgamma.

I am attempting to use lgamma from C's math.h in Perl6.

如何将其合并到 Perl6 中?

How can I incorporate this into Perl6?

我试过了

use NativeCall;

sub lgamma(num64 --> num64) is native(Str) {};

say lgamma(3e0);

my $x = 3.14;
say lgamma($x);

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

This works for the first number (a Str) but fails for the second, $x, giving the error:

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 中做到这一点.

I want to do this very simply, like in Perl5: use POSIX 'lgamma'; and then lgamma($x) but I don't see how to do that in Perl6.

推荐答案

原生值的错误并不总是很清楚.

The errors with native values isn't always clear.

基本上是说 Rat 不是 Num.

Basically it is saying that a Rat isn't a Num.

3.14 是一只老鼠.(理性)

3.14 is a Rat. (Rational)

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

<小时>

每次调用时都可以将值强制为 Num.


You could just always coerce the value to Num everytime you call it.

lgamma( $x.Num )

这看起来不太好.

我只想将本机 sub 包装在另一个将所有实数强制为 Num 的子中.
(实数除复数外都是数字)

I would just wrap the native sub in another one that coerces all Real numbers to Num.
(Real is all Numeric except Complex)

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

这篇关于使用 NativeCall 将 C 库函数合并到 Perl6 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆