Skip to content

R as shared library

3 messages · Jeffrey Horner, Byron Ellis

#
Hello folks,

I'm embarking on a project to embed R into the Apache web server, and 
I'd like your help. Currently, I'm looking for a way for R code to call 
back into a shared library from which the R shared library was loaded.

Essentially, apache starts and loads mod_R.so which runs an 
initialization routine which calls  Rf_initEmbeddedR() and the following 
code:

  /* override to call apache library write routine */
  ptr_R_WriteConsole = Rapache_WriteConsole;

  /* load source(). I assume this is appropriate. I could
     always move this to the code that handles the requst */
  PROTECT(R_source_fun = allocVector(LANGSXP, 2));
  SETCAR(R_source_fun, Rf_install("source"));
  SETCAR(CDR(R_source_fun), R_source_arg = NEW_CHARACTER(1));

Then each request is serviced by the following code:

  /* r is apache request, r->filename is url translated to
     apsolute path to filename */
  SET_STRING_ELT(R_source_arg, 0, COPY_TO_USER_STRING(r->filename));
  errorOccurred=1;
  /* R code: source(filename) */
  val = R_tryEval(R_source_fun,NULL,&errorOccurred);
  if (errorOccurred){
    // Send a message to stderr (apache redirects this to the error log)
    fprintf(stderr,"apache2_mod_R: source(%s) failed!\n",r->filename);
    fflush(stderr);
  } else {
    return ok;
  }

I would like to write R routines which hook into apache specific library 
calls to get at the CGI and system data. The apache specific calls need 
a request structure (the r variable) which is available in mod_R.so 
(already loaded) on each request. If I use the .C, .Call, or .External 
interface, then I must load a shared library with the appropriate 
routines. I would like to place those routines in mod_R.so to take 
advantage of access to the request structure. Is this doable?

Another approach is to turn the CGI data into R variables and just place 
those in the top level environment, foregoing any callbacks into apache 
again until the R code has run to completion. This is similar to how PHP 
is embedded into Apache. Other languages that _do_ provide callbacks 
into apache include Perl, Python, and Ruby.
2 days later
#
Building the callbacks is possible. Basically, you need to construct a 
fake DllInfo object for Apache and then use R_registerRoutines to 
attach the callbacks to R as it if were a normal R package registering 
its routines.

I might have a simple example of this lying around, I'll see if I can 
find it (especially since it seems I'll be needing it myself soon :-))
On Aug 18, 2004, at 1:08 PM, Jeffrey Horner wrote:

            
---
Byron Ellis (bellis@hsph.harvard.edu)
"Oook" -- The Librarian
#
Byron Ellis wrote:
Yes. I thought about that, but that solution may break on future R 
releases and may hinder porting to other platforms outside of the UNIX 
family. I'm going to try Duncan's suggestion of a third dll which will 
install like a traditional R package.