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

JJ Allaire jj.allaire at gmail.com
Sat May 18 21:45:29 CEST 2013


Hi Xiao,

The problem is that sourceCpp can only accept arguments of types that can
be converted to R using Rcpp::as (this is detailed in the help topic for
sourceCpp and in the Rcpp vignettes). Plain C function pointers
aren't convertible in this fashion so the compilation fails.

If your intention is to pass an R function to C++ you can however use the
Rcpp::Function type in your signature. This is explained in more detail in
this Rcpp Gallery article:

http://gallery.rcpp.org/articles/r-function-from-c++/

J.J.

On Sat, May 18, 2013 at 1:31 PM, Xiao He <praguewatermelon at gmail.com> wrote:

> 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
>
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130518/005f5c5b/attachment.html>


More information about the Rcpp-devel mailing list