[Rcpp-devel] function within a function

Marie Auger-Methe marie.augermethe at gmail.com
Thu May 3 12:11:07 CEST 2012


Thank you for your prompt response!

Sorry, this was more a C++ question. I'm still having a hard time to 
disentangle all of these methods and languages.

It worked! I have included below the .R, .h, and .cpp files of the fx 
from my previous e-mail. Just to help the next newbie ;) .

Thanks!

Marie

f1.cpp:
#include "f1.h"

SEXP f1(){
     using namespace Rcpp ;

   NumericVector x(1);
   x = 9;
   return x;
}

f1.h:
#ifndef _fxwithinfx_f1_H
#define _fxwithinfx_f1_H

#include <Rcpp.h>

extern "C" SEXP f1() ;

#endif

f2.cpp:
#include "f1.h"
#include "f2.h"

SEXP f2(){
   using namespace Rcpp;
   NumericVector x = f1();
   x[0] = x[0] + 1;
   return x;
}

f2.h:
#ifndef _fxwithinfx_f2_H
#define _fxwithinfx_f2_H

#include <Rcpp.h>

RcppExport SEXP f2() ;

#endif

f2.R:
f2 <- function(){
     .Call( "f2", PACKAGE = "fxwithinfx" )
}


On 02/05/2012 4:18 PM, Dirk Eddelbuettel wrote:
> Marie,
>
> On 2 May 2012 at 15:49, Marie Auger-Methe wrote:
> | Dear list,
> |
> | Still pretty new to Rcpp and C++. I am trying to make a package that has
> | multiple Rcpp functions. Some of the Rcpp functions call other Rcpp
> | functions and I am wondering what is the most efficient method to handle
> | this situation. Here is a example of how I am handling the function
> | within function (examplified using inline rather than .cpp and .h file):
>
> Don't use inline for this. It generates randomized function 'names' at the
> C++ level at it is tailored for use _from R_ and the C++ function pointer
> gets hidden away in an R function.
>
> It is time to think about packages.  Inline is very convenient, but it has
> occassional limits. You are hitting one now.
>
> What you want is trivial and can be fixed the standard C / C++ by declaring
> the function headers as eg in
>
>     extern "C" SEXP foo(SEXP a, SEXP b);
>
>     extern "C" SEXP bar(SEXP c, SEXP d);
>
> before you implement the functions.   Now you can call any way you want foo
> calling foo, foo calling bar, bar calling foo, bar calling bar, ...
>
> And of course you do not need to use the   SEXP name(SEXP a, SEXP b)
> convention use by R.  You only need this when you call from R via .Call(). At
> the C++ level you are open to any other (visible) C++ function -- which is
> how we call other libraries.
>
> My last piece of advice would be to write a mock C++ solution first. Write a
> short main(), set up some data, call one function, have it call another.
>
> Then work out Rcpp packages which you have meant to do for a while now :-)
> and wrap it around your initial C++ program, replacing the main() function
> which one you can call from R.  And then you're done.
>
> Dirk
>



More information about the Rcpp-devel mailing list