From jeff.horner at vanderbilt.edu  Wed Aug 18 19:08:52 2004
From: jeff.horner at vanderbilt.edu (Jeffrey Horner)
Date: Wed Aug 18 19:08:09 2004
Subject: [Rd] R as shared library
Message-ID: <41238D24.3020108@vanderbilt.edu>

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.


-- 
Jeffrey Horner       Computer Systems Analyst         School of Medicine
615-322-8606         Department of Biostatistics   Vanderbilt University


[Rd] R as shared library
Jeffrey Horner