我正在尝试开发一个包,其中我需要输入用户的函数(可以使用定义Rcpp
or in R
),将其发送到另一个函数(在包内)struct
并在那里处理它。
当我使用Rcpp::Xptr
(即函数指针)代码可以工作,但同样不起作用Rcpp::Function
。使用的优点Rcpp::Function
对于用户来说,他们将能够在中定义函数R
(尽管损失了很多性能增益)。
首先什么有效:
#include <Rcpp.h>
using namespace Rcpp;
// define the structure
struct xptr_data{
SEXP xptr;
};
// a minimal function (user-defined)
// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
return x * 2;
}
// pointer to function defined
typedef NumericVector (*funcPtr) (NumericVector y);
// [[Rcpp::export]]
XPtr<funcPtr> putFunPtrInXPtr() {
XPtr<funcPtr> rhs_ptr(new funcPtr(×Two), false);
return rhs_ptr;
}
// this function will be in the package
NumericVector call_by_xptr_struct(NumericVector y, void* user_data){
struct xptr_data *my_rhs_ptr = (struct xptr_data*)user_data;
SEXP xpsexp = (*my_rhs_ptr).xptr;
// use function pointer to get the derivatives
XPtr<funcPtr> rhs_xptr(xpsexp);
funcPtr rhs_fun = *rhs_xptr;
// use the function to calculate value of RHS ----
return(rhs_fun(y));
}
// using xptr to evaluate function - this will be exported
// from the package
//[[Rcpp::export]]
NumericVector xptr_call_struct(NumericVector y, SEXP xpsexp){
struct xptr_data my_xptr = {NULL};
my_xptr.xptr = xpsexp;
return call_by_xptr_struct(y, (void*)&my_xptr);
}
/*** R
rhs_ptr <- putFunPtrInXPtr()
xptr_call_struct(c(1,2), rhs_ptr)
[1] 2 4
*/
什么不起作用,
如果函数定义在R
我用Rcpp::Function
直接导致整个 R 会话崩溃,
#include <Rcpp.h>
using namespace Rcpp;
// define the function based structure
struct func_data{
Function func;
};
// processes the input function
NumericVector call_by_func_struct(NumericVector y, void* user_data){
struct func_data *my_rhs_fun = (struct func_data*)user_data;
Function func = (*my_rhs_fun).func;
return(func(y));
}
// this will be exported from the package
//[[Rcpp::export]]
NumericVector func_call_struct(NumericVector y, Function func){
struct func_data my_func = {NULL};
my_func.func = func;
return call_by_func_struct(y, (void*)&my_func);
}
/*** R
timesThree <- function(y){
y <- 3 * y
y
}
*/
上面的代码编译得很好,但是当我调用该函数时func_call_struct(c(1,2), timesThree))
,它会导致整个 R 会话崩溃。
有关原因的任何指导R
崩溃以及如何输入定义的函数R
会很有帮助的。
此外,有什么方法可以传递定义在的输入函数Rcpp
(e.g., timesTwo
上面)而不是他们的Xptr
。我认为这对于最终用户来说不会那么混乱(因为他们不必生成函数指针),而不会牺牲随之而来的速度Rcpp
.