I have this function to connect R with MYSQL and return the connection as global variable to be used in other functions later on. The parameters should be taken from the user. I would like to call this function from Qt creator using RInside and Rcpp libraries.
connection <- function(username,passwords,databaseName){
#' create connection with selected database
ConnectedDb <- DBI::dbConnect(RMariaDB::MariaDB(), user=username,
password=passwords, dbname=databaseName,
host='localhost')
con <<- ConnectedDb
#' assign the connection as global variable
assign("con", ConnectedDb, envir = .GlobalEnv)
#' return the connection
return(con)}
I added RInside and Rcpp to my Qt project and applied the project suggested in https://github.com/eddelbuettel/rinside/tree/master/inst/examples/qt . The project worked fine.
I appreciate any suggestions.
UPDATE: I understand that I need to put the function inside R.parseEvalQ and then call it using R.parseEval. A summary of what I did:
#include <R.h>
#include <RInside.h>
#include <Rcpp.h>
#include <mysql.h>
#include <driver.h>
int main(int argc, const char * argv[]) {
RInside R(argc, argv);
string username,passwords,databaseName;
R["username"] = "root";
R["passwords"] = "pass";
R["databaseName"] = "Test";
// define R function in C++ environment
R.parseEvalQ("connection <- function(username,
passwords,databaseName){ConnectedDb <<-
DBI::dbConnect(RMariaDB::MariaDB(),user=username,password=passwords,
dbname=databaseName,host='localhost'); con <<- ConnectedDb;
assign('con', ConnectedDb, envir = .GlobalEnv); con}");
// call R function in C++ environment
R.parseEval("connection(username,passwords,databaseName)");
return 0;
}
Now I would like to test the function (if it work probably or not). I need to assign variable equal to R.parseEval to print it out. I added the following code:
sql::Connection *con;
con = R.parseEval("connection(username,passwords,databaseName)");
It gave the following error:
Cannot initialize a member subobject of type 'sql::Connection *' with an lvalue of type 'SEXP' (aka 'SEXPREC *')
When I use Rcpp::List as follow:
Rcpp::List c;
c = R.parseEval("connection(username,passwords,databaseName)");
I got the following error:
/Library/Frameworks/R.framework/Versions/4.0/Resources/library/Rcpp/include/Rcpp/internal/wrap.h:503:18 No viable conversion from 'const RInside::Proxy' to 'SEXP' (aka 'SEXPREC *')
Which object in Rcpp or c++ will be equal to returned connection ? because I tried so many types and nothing worked. For now I do not guarantee that the connection is established !