Questions
- Is it bad practice to compile shared libraries from inside an R session using
system()orshell()then dynamically load them? - 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
- changes the value of a macro variable in a template C source file,
- gives the edited source file a new name,
- compiles a shared library of the new program, and
- 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.