根据http://gallery.rcpp.org/articles/r-function-from-c++,Rcpp允许用户从C++中调用R函数。那么在Fortran中是否有类似的东西,使得人们可以在Fortran代码中调用R函数?
iso_c_binding
来与C进行接口。#include <iostream>
#include <RInside.h>
void helloR_(int argc, char *argv[], const char *msg);
extern "C" void helloR(int argc, char *argv[], const char *msg) {
// create an embedded R instance
RInside R(argc, argv);
// convert to string for RInside assignment
std::string txt = std::string(msg);
// C++ Notice
std::cout << "This is C++, " << txt << std::endl;
// Assign string to R object
R.assign(txt, "txt");
// eval the string, give R notice
R.parseEvalQ("cat('This is R, ', txt, '\n')");
}
testF.f
PROGRAM MAIN
USE iso_c_binding
IMPLICIT NONE
INTEGER :: argc
CHARACTER(len=32) :: arg
CHARACTER(len=32) :: msg
INTERFACE
SUBROUTINE R_FUN(argc, arg, msg) bind(C, name="helloR")
USE iso_c_binding
INTEGER(kind=c_int), INTENT(IN) :: argc
CHARACTER(kind=c_char), INTENT(IN) :: arg(*)
CHARACTER(kind = C_CHAR), INTENT(IN) :: msg(*)
END SUBROUTINE R_FUN
END INTERFACE
print *, "Fortran Calling RInside"
CALL R_FUN (argc, arg, "Hello World"//C_NULL_CHAR)
END PROGRAM
gfortran -c testF.f
由于必须知道R、Rcpp和RInside的包含目录的位置,因此C++编译有点棘手。
g++ testC.cpp -c -I/path/to/RInside/include -I/path/to/Rcpp/include -I/usr/share/R/include
然后,您需要提供正确的库和 lgfortran
标志进行链接。
g++ -o fcr testF.o testC.o -L/usr/lib/R/lib -lR -L/path/to/RInside/lib/ -lRInside -L/path/to/Rcpp/libs/ -Wl,-rpath,/home/path/to/RInside/lib/ -lRInside -Wl,-rpath,/path/to/Rcpp/libs/ -lgfortran
./fcr
Fortran Calling RInside
This is C++, Hello World
This is R, Hello World
EXECUTE_COMMAND_LINE
(标准Fortran 2003)或类似SYSTEM
(常见扩展名)的命令来调用一个R脚本,该脚本将其结果写入文件,然后从Fortran程序中读取这些结果。