Calling R Function from C++

后端 未结 2 1966
情话喂你
情话喂你 2020-11-28 20:23

I would like to, within my own compiled C++ code, check to see if a library package is loaded in R (if not, load it), call a function from that library and get the results b

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 20:57

    There is Rcpp which allows you to easily extend R with C++ code, and also have that C++ code call back to R. There are examples included in the package which show that.

    But maybe what you really want is to keep your C++ program (i.e. you own main()) and call out to R? That can be done most easily with RInside which allows you to very easily embed R inside your C++ application---and the test for library, load if needed and function call are then extremely easy to do, and the (more than a dozen) included examples show you how to. And Rcpp still helps you to get results back and forth.

    Edit: As Martin was kind enough to show things the official way I cannot help and contrast it with one of the examples shipping with RInside. It is something I once wrote quickly to help someone who had asked on r-help about how to load (a portfolio optimisation) library and use it. It meets your requirements: load a library, accesses some data in pass a weights vector down from C++ to R, deploy R and get the result back.

    // -*- mode: C++; c-indent-level: 4; c-basic-offset: 4;  tab-width: 8; -*-
    //
    // Simple example for the repeated r-devel mails by Abhijit Bera
    //
    // Copyright (C) 2009         Dirk Eddelbuettel 
    // Copyright (C) 2010 - 2011  Dirk Eddelbuettel and Romain Francois
    
    #include                     // for the embedded R via RInside
    
    int main(int argc, char *argv[]) {
    
        try {
            RInside R(argc, argv);          // create an embedded R instance 
    
            std::string txt = "suppressMessages(library(fPortfolio))";
            R.parseEvalQ(txt);              // load library, no return value
    
            txt = "M <- as.matrix(SWX.RET); print(head(M)); M";
            // assign mat. M to NumericMatrix
            Rcpp::NumericMatrix M = R.parseEval(txt); 
    
            std::cout << "M has " 
                      << M.nrow() << " rows and " 
                      << M.ncol() << " cols" << std::endl;
    
            txt = "colnames(M)";        // assign columns names of M to ans and
            // into string vector cnames
            Rcpp::CharacterVector cnames = R.parseEval(txt);   
    
            for (int i=0; i

    This rinside_sample2.cpp, and there are lots more examples in the package. To build it, you just say 'make rinside_sample2' as the supplied Makefile is set up to find R, Rcpp and RInside.

提交回复
热议问题