简体   繁体   English

如何在R包中调用C函数

[英]How to call a C function in R package

The package has name pareto . 该软件包的名称为pareto This is the .c file in the src directory: 这是src目录中的.c文件:

#include <R.h>
#include <math.h>
#include "Rinternals.h"
#include "R_ext/Rdynload.h"

static void dpareto(double *x, double *a, double *b, int *n, int *islog,
                           double *den){
    int length = n[0];
    int i;
    int isLog = islog[0];
    for (i = 0; i < length; i++){
        if (a[i] > 0 && b[i] > 0) {
            if (x[i] > a[i])
                den[i] = log(b[i]) + b[i] * log(a[i]) - (b[i] + 1) * log(x[i]);
            else
                den[i] =  R_NegInf;
            if (!isLog)
                den[i] = exp(den[i]);
        }
        else {
            den[i] = R_NaN;
        }
    }
}

static R_CMethodDef DotCEntries[] = {
    {"dpareto", (DL_FUNC) dpareto, 6},
    {NULL}
};

void R_init_pareto(DllInfo *info)
{
    R_registerRoutines(info, DotCEntries, NULL, NULL, NULL);
}

In R directory, the corresponding .R file is: R目录中,相应的.R文件为:

#' @useDynLib pareto
#' @export
dpareto <- function(x, a, b, log = FALSE) {
    nx <- length(x)
    na <- length(a)
    nb <- length(b)
    n <- max(nx, na, nb)
    if (nx < n) x <- rep(x, length.out = n)
    if (na < n) a <- rep(a, length.out = n)
    if (nb < n) b <- rep(b, length.out = n)
    rt <- .C("dpareto", as.double(x), as.double(a), as.double(b), as.integer(n),
             as.integer(log), den = double(n), PACKAGE="pareto")
    rt$den

}

After documented by roxygen , the NAMESPACE has: roxygen记录后, NAMESPACE具有:

export(dpareto)
useDynLib(pareto)

But the package cannot pass checking, and R keeps generate error message that: 但是该程序包无法通过检查,并且R不断生成以下错误消息:

 "dpareto" not available for .C() for package "pareto"
Calls: dpareto -> .C

I really can't figure out which step I made a mistake. 我真的不知道我在哪一步做错了。

You added the static keyword to your dpareto function definition. 您将static关键字添加到dpareto函数定义中。 This means the function won't be exported, so R won't see it. 这意味着该函数将不会导出,因此R不会看到它。 Remove static and try again. 删除static然后重试。

trivial mistake. 琐碎的错误。 Just in void R_init_pareto I used a wrong package name. 只是在void R_init_pareto我使用了错误的程序包名称。 So silly mistake. 如此愚蠢的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM