How to change a C macro variable (preprocessor define directive) from inside an R session?

Viewed 1691

Questions

  1. Is it bad practice to compile shared libraries from inside an R session using system() or shell() then dynamically load them?
  2. Is there a "better" way (than the code below) to change the value of a macro variable in a C source file based on user input from an R session?

Background

Objective

In an R session, I want to create a function that

  1. changes the value of a macro variable in a template C source file,
  2. gives the edited source file a new name,
  3. compiles a shared library of the new program, and
  4. dynamically loads the new shared library into the current R session

Call the template C source file template.tmp and let it look something like:

...
#define VAR
...

(I don't plan on actually compiling template.tmp, hence the .tmp file extension. I merely use it as a template to create other source files where only the #define directive changes.)

Below is the R function, I created to do the steps above. For simplicity, I removed lines of code that declare correct path names or add portability to Windows and other Unix-alikes.

myfunc <- function(val){
  # create commands for system()
  subst_cmd <- paste0("sed 's/define VAR/define VAR ", val, "/' template.tmp > newprog.c")
  shlib_cmd <- paste0("R CMD SHLIB newprog.c")

  # submit commands to system()
  system(subst_cmd)
  system(shlib_cmd)

  # dynamically load shared library
  dyn.load(newprog.so)
}

Thus, myfunc(12345) will create a new C source file with the following lines, and will also compile it to a shared library and dynamically load it into the current R session.

...
#define VAR 12345
...

Motivation

I have a function where speed is very important as the function could be called thousands of times. Passing values to the function in my C source file tremendously slows down the speed when compared to using a #define preprocessor directive. My thinking was to some how edit the file within R then compile it and load it into the R session. But I do not know if this is good practice or if there is another way to accomplish the same task. One problem I have already encountered occurs when I remote into a computer cluster where the login node has compiling capabilities but the computing nodes do not.

1 Answers
Related