简体   繁体   中英

How to call a C function in R package

The package has name pareto . This is the .c file in the src directory:

#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:

#' @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:

export(dpareto)
useDynLib(pareto)

But the package cannot pass checking, and R keeps generate error message that:

 "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. This means the function won't be exported, so R won't see it. Remove static and try again.

trivial mistake. Just in void R_init_pareto I used a wrong package name. So silly mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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