将C函数导入Perl程序

con*_*con 4 c perl

我想导入我写的C函数

#include <math.h>
#include <stdio.h>

double function (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {//calculate a p-value based on an array
....
}
int main(){
....
}
Run Code Online (Sandbox Code Playgroud)

进入perl脚本,我看过Inline :: C和XS,但我看不到如何使用它们,我无法通过这些示例,我还需要lgamma函数.该函数将2个数组作为输入.

有人能够提供一个例子,我可以在导入C的math.h时将其导入perl脚本吗?

mob*_*mob 5

这个问题的棘手部分是将Perl数组从Perl传递给C.

一种方法是使用两个步骤.将Perl数组(AV*在C中)转换为double数组,然后调用您的函数.这里使用的perl函数和宏记录在perlguts

use Inline 'C';
@a = (1,2,3,4,5);
@b = (19,42);
$x = c_function(\@a,\@b);
print "Result: $x\n";
__END__
__C__
#include <stdio.h>
#include <math.h>
double *AV_to_doubleptr(AV *av, int *len)
{
    *len = av_len(av) + 1;
    double *array = malloc(sizeof(double) * *len);
    int i;
    for (i=0; i<*len; i++)
        array[i] = SvNV( *av_fetch(av, i, 0) );
    return array;  /* returns length in len as side-effect */
}

double the_real_function(const double *x1, int n1, const double *x2, int n2)
{
    ...
}

double c_function(AV *av1, AV *av2)
{
    int n1, n2;
    double *x1 = AV_to_doubleptr(av1, &n1);
    double *x2 = AV_to_doubleptr(av2, &n2);
    double result = the_real_function(x1,n1, x2,n2);
    free(x2);
    free(x1);
    return result;
}
Run Code Online (Sandbox Code Playgroud)