如何从Fortran调用R函数? [英] How to call R functions from Fortran?
问题描述
根据 http://gallery.rcpp.org/articles/r-function-from-c++ Rcpp允许用户从C ++调用R函数.在那儿 在Fortran中类似的东西,以便人们可以在其中调用R函数 Fortran代码?
According to http://gallery.rcpp.org/articles/r-function-from-c++ Rcpp allows users to call R functions from C++. Is there something similar in Fortran so that people can call R function in Fortran code?
推荐答案
我相信您应该查看 RFortran ? AFAIK是R对象的唯一Fortran绑定,而且它是开源的.
I believe you should look at RFortran? AFAIK it is the only Fortran bindings of R objects, plus it is open source.
编辑
根据下面的评论,我没有意识到RFortran仅适用于Windows.因此,为了获得更可移植的答案,让我们创建一个示例,在该示例中,我将利用 RInside 将R函数嵌入C ++代码更简单.我也将使用iso_c_binding
与C进行接口.
As per the comments below, I was unaware that RFortran was only applicable on Windows. So, for a more portable answer let's create an example where I will leverage the RInside which makes embedding R functions in C++ code simpler. I also would use the iso_c_binding
to interface with C.
testC.cpp
testC.cpp
#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
Fortran编译很简单:
The Fortran compilation is simple:
gfortran -c testF.f
鉴于您必须知道R,Rcpp和RInside的包含目录位于何处,因此C ++编译有些棘手.
The C++ compilation is a little tricky given that you must know where your include directories are for R, Rcpp, and RInside are located.
g++ testC.cpp -c -I/path/to/RInside/include -I/path/to/Rcpp/include -I/usr/share/R/include
然后,您需要提供正确的库和lgfortran
标志的链接.
Then the linking you need to provide the correct libraries and the lgfortran
flag.
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
现在我有一个小程序,演示如何从Fortran访问R函数
Now I have a small program demonstrating how to access R functions form Fortran
./fcr
Fortran Calling RInside
This is C++, Hello World
This is R, Hello World
这篇关于如何从Fortran调用R函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!