使用.C()从R调用编译的C

时间:2011-01-16 20:57:27

标签: c r

我正在尝试从R调用C可执行文件getNBDensities中的函数measurementDensities_out。该函数传递了几个数组和变量double runsum。现在,getNBDensities函数基本上什么都不做:它打印以筛选传递参数的值。我的问题是调用函数的语法:

array(.C("getNBDensities",
            hr = as.double(hosp.rate), # a vector (s x 1)
            sp = as.double(samplingProbabilities), # another vector (s x 1)
            odh = as.double(odh), # another vector (s x 1)
            simCases = as.integer(x[c("xC1","xC2","xC3")]), # another vector (s x 1)
            obsCases = as.integer(y[c("yC1","yC2","yC3")]), # another vector (s x 1)
            runsum = as.double(runsum), # double
            DUP = TRUE, NAOK = TRUE, PACKAGE = "measurementDensities_out")$f,
            dim = length(y[c("yC1","yC2","yC3")]),
            dimnames = c("yC1","yC2","yC3"))

在正确执行该功能后(即右侧输出打印到屏幕上),我得到的错误是

Error in dim(data) <- dim : attempt to set an attribute on NULL

我不清楚我应该传递函数的维度是什么:它应该是s x 5 + 1(长度为s的五个向量和一个双倍)?我尝试过各种各样的组合(包括s x5 + 1)并且在网上找到了看似相互矛盾的描述/示例。这里应该发生什么。

对于那些感兴趣的人,C代码如下:

#include <R.h>
#include <Rmath.h>
#include <math.h>
#include <Rdefines.h>
#include <R_ext/PrtUtil.h>
#define NUM_STRAINS 3
#define DEBUG
void getNBDensities(  double *hr, double *sp, double *odh, int *simCases, int *obsCases, double *runsum );
void getNBDensities( double *hr, double *sp, double *odh, int *simCases, int *obsCases, double *runsum ) {
#ifdef DEBUG
  for ( int s = 0; s < NUM_STRAINS; s++ ) {
    Rprintf("\nFor strain %d",s); 
    Rprintf("\n\tHospitalization rate = %lg", hr[s]);
    Rprintf("\n\tSimulation probability = %lg",sp[s]);
    Rprintf("\n\tSimulated cases = %d",simCases[s]);
    Rprintf("\n\tObserved cases = %d",obsCases[s]);
    Rprintf("\n\tOverdispersion parameter = %lg",odh[s]);
}
  Rprintf("\nRunning sum = %lg",runsum[0]);
#endif
}


天真的解决方案

虽然可能存在更好(即,可能更快或语法更清晰)的解决方案(参见Dirk的答案),但以下代码的简化有效:

#include <R.h>

可以在#include <Rmath.h>

中访问变量

1 个答案:

答案 0 :(得分:4)

您可能希望查看inline包,它可以轻松地编译,链接和加载C,C ++或Fortran代码。

那就是说,特别是如果C ++是你的另一个选择,也可以查看Rcpp包,它允许你轻松地来回传输R和C ++对象。