[Rcpp-devel] Pass a function name as an argument.

Xiao He praguewatermelon at gmail.com
Sat May 18 19:31:51 CEST 2013


Hi everyone, I have two questions regarding passing a function name as an
argument.

(1). Suppose that I have a function foo() shown below. The function takes a
NumericVector and a function pointer that points to a function that takes a
NumericVector and returns a double. Note that the function pointer will
only point to functions not exposed to R.

double foo(NumericVector x, double (*f)(NumericVector x) ){
double output;
 output=(*f)(x);
return output;
}

When I try to compile it as is using sourceCpp(), it's fine, but when I add
"// [[Rcpp::export]]" above the function definition, I get an error message:

Error in sourceCpp("foo.cpp") :
  Error 1 occurred building shared library.
foo.cpp:229: error: expected initializer before ‘SEXP’

So I wonder how I can fix this mistake.


(2). Imagine a more complex scenario: suppose there are two functions
available to be passed to foo(). But the two functions differ in the number
of arguments each has (see fun1() and fun2() below). I wonder if there is
any way to deal with this.

double fun1(NumericVector x){
double total=0;
 for(int i=0;i<x.size();i++)
total+=x(i);
 return total/10;
}


double fun2(NumericVector x, int n){
double total=0;
 for(int i=0;i<x.size();i++)
total+=x(i)+add;
 return total/n;
}
 Thank you in advance!


Best,
-Xiao
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130518/16c975c9/attachment.html>


More information about the Rcpp-devel mailing list