【问题标题】:How to call a C function in R package如何在 R 包中调用 C 函数
【发布时间】:2017-03-07 00:12:22
【问题描述】:

包的名称为pareto。这是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);
}

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

}

roxygen 记录后,NAMESPACE 有:

export(dpareto)
useDynLib(pareto)

但是包无法通过检查,并且R不断生成错误消息:

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

我真的不知道是哪一步出错了。

【问题讨论】:

  • .c 函数是正确的,我在包中以外的地方成功调用了它。

标签: c r r-package


【解决方案1】:

您已将 static 关键字添加到您的 dpareto 函数定义中。这意味着该函数不会被导出,所以 R 不会看到它。删除static,然后重试。

【讨论】:

  • Bs He:确保已加载共享库,即检查文件NAMESPACE 是否有useDynLib("pareto")
【解决方案2】:

小错误。就在void R_init_pareto 中,我使用了错误的包名。真是愚蠢的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多