问题描述
我想打电话从数值积分包在C A C ++程序函数执行多维整合。
I'm trying to call a C routine from the cubature package in a c++ function to perform multidimensional integration.
我试图重现基本科研的例子是
The basic R example I'm trying to reproduce is
library(cubature)
integrand <- function(x) sin(x)
adaptIntegrate(integrand, 0, pi)
我可以称之为从这个RCPP R函数如下 href=\"http://gallery.rcpp.org/articles/r-function-from-c++/\">这个配方,但将是从C / C ++来R.它似乎更为明智来直接调用C函数从C ++来回切换的性能损失。
I could just call this R function from Rcpp following this recipe from the gallery, but there would be some performance penalty in switching back and forth from c/c++ to R. It seems more sensible to directly call the C function from C++.
C例程 adapt_integrate
是数值积分
导出的
// R_RegisterCCallable("cubature", "adapt_integrate", (DL_FUNC) adapt_integrate);
我不知道如何把它从C ++调用然而,。这里是我的蹩脚的尝试,
I don't understand how to call it from c++, however. Here's my lame attempt,
sourceCpp(code = '
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double integrand(double x){
return(sin(x));
}
// [[Rcpp::depends(cubature)]]
// [[Rcpp::export]]
Rcpp::List integratecpp(double llim, double ulim)
{
Rcpp::Function p_cubature = R_GetCCallable("cubature", "adapt_integrate");
Rcpp::List result = p_cubature(integrand, llim, ulim);
return(result);
}
'
)
integratecpp(0, pi)
这编译失败;显然,我做的事情很无聊,并丢失了一些重要的措施来 R_GetCCallable
的输出转换成 RCPP ::功能
(或者直接打电话吗?)。我读过一些相关的帖子处理函数指针,但还没有看到使用外部C函数的例子。
This fails to compile; clearly I'm doing something very silly and missing some important steps to convert the output of R_GetCCallable
into an Rcpp::Function
(or call it directly?). I've read several related posts dealing with function pointers, but haven't seen an example using an external C function.
推荐答案
不幸的是数值积分
不出货的头在安装/包括
,所以你不得不借,从他们的,做这样的事情在你的code:
Unfortunately cubature
does not ship the headers in inst/include
, so you have to borrow that from them and do something like this in your code:
typedef void (*integrand) (unsigned ndim, const double *x, void *,
unsigned fdim, double *fval);
int adapt_integrate(
unsigned fdim, integrand f, void *fdata,
unsigned dim, const double *xmin, const double *xmax,
unsigned maxEval, double reqAbsError, double reqRelError,
double *val, double *err)
{
typedef int (*Fun)(unsigned,integrand,void*,unsigned,
const double*,const double*, unsigned, double, double, double*, double*) ;
Fun fun = (Fun) R_GetCCallable( "cubature", "adapt_integrate" ) ;
return fun(fdim,f,fdata,dim,xmin,xmax,maxEval,reqAbsError, reqRelError,val,err);
}
这可能是与数值积分
的维护者,在他船声明安装/包括
来negociate一个好主意这样你只需要使用 LinkingTo
。
It might be a good idea to negociate with the maintainer of cubature
that he ships declarations in inst/include
so that you'd only have to use LinkingTo
.
这篇关于使用C函数在其他RCPP包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!