How to initialize "RInside" instance in a function NOT main function, and call it multiple times without getting "R is already initialized"?

126 views Asked by At

I would like to use RInside in a function that is NOT the main function in my c++ program. After debugging, I found out that the function works for the first round and I get the output as expected but when it is called for the second time my program stops and I get the error message "R is already initialized". Can anybody help me to have a workaround to overcome this issue? please see below a simple example to clarify that. I need to call mainR() function from a function(my_func) that is also NOT the main function.I am actually dealing with a bit complex program so my_func will be also called multiple times, which made initializing RInside useless.. Sorry, the code doesn't look realistic but I just wanted to simplify and clarify my question.

#include <RInside.h> 

void mainR()
{

    RInside R; // create an embedded R instance

    R["txt"] = "Hello, world!\n"; // assign a char* (string) to 'txt'

    R.parseEvalQ("cat(txt)"); // eval the init string, ignoring any returns

}

void my_func()
{

mainR();
mainR();
.
.
}
1

There are 1 answers

0
JaMiT On BEST ANSWER

It would appear (I am not an expert on RInside) that an application must have no more than one RInside object created over the course of an application's lifetime. This corresponds to C++'s concept of "static storage duration". When a variable is defined in the main function, the difference between "automatic" (the default) and "static" duration is usually insignificant, but it is highly significant for a function called more than once.

Adding the keyword static indicates that a variable is to have static storage duration.

static RInside R; // create an embedded R instance

This has two effects on a variable defined inside a function. First, the object is not destroyed when the function ends. Second, the object is not re-initialized when the function is called again. (It is still initialized when the function is called the first time.) This avoids the error where R was initialized twice. However, it also comes with a caveat—the object retains state between function calls. One must assume that the RInside object might have been used earlier, even at the beginning of mainR().