Skip to content
Prev 43199 / 63424 Next

Creating a package which contains stand-alone C code

On Apr 27, 2012, at 9:54 AM, Rajen Shah wrote:

            
Simply add a target for your executable to Makevars.
Yes, you can have a look at Rserve (preferably the development version) for both of the above. It is not the perfect example (because it grew organically and is a bit more complex) but it does exactly that.
Conceptually, you can achieve the same thing without another executable by forking and calling the main() function of your program -- that way you don't need another executable yet you can compile your code either as a stand-alone program (for testing) or as a package (for deployment):

SEXP call_main(SEXP args) {
   int argc = LENGTH(args), i;
   pid_t pid;
   char **argv = (char**) calloc(argc + 1, sizeof(char*));
   for (i = 0; i < argc; i++) argv[i] = CHAR(STRING_ELT(args, i));
   if ((pid = fork()) == 0) { main(argc, argv); exit(0); }
   return ScalarInteger(pid);
}

and PKG_CPPFLAGS=-Dmain=prog_main make sure you re-map main for the package in case it conflicts with R.

In general, you can do better and pass your data directly -- just define some interface in your program -- it will be much more efficient than going through files. Then your main() for the stand-alone program will read in the files and call that interface whereas R will call it directly.

Cheers,
Simon