Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing functions in R as .Fortran arguments

Tags:

r

fortran

After spending some days already searching for something like this on the internet, I still couldn't manage to find anything describing this problem. Reading through the (otherwise quite recommendable) 'Writing R Extensions' dind't offer a solution as well. Thus, here's my most urgent question:

Is it possible to pass functions (for simplicity's sake, assume a simple R function - in reality, the problem is even uglier) as function/subroutine parameters to Fortran via .Fortran(...) call - and if so, how?

I wrote two simple functions in order to test this, first a Fortran subroutine (tailored to use the function I originally intended to pass, thus the kinda weird dimensions in the interface):

subroutine foo(o, x)
    implicit none

    interface
        subroutine o(t, y, param, f)
            double precision, intent(in) :: t
            double precision, dimension(58), intent(in) :: y, param
            double precision, dimension(22), intent(out) :: f
        end subroutine
    end interface

    double precision, dimension(22), intent(out) :: x

    double precision, dimension(58) :: yt, paramt
    integer :: i

    do i = 1, 58
        yt(i) = rand(0)
        paramt(i) = rand(1)
    end do

    call o(dble(4.2), yt, paramt, x)
end subroutine

and a simple R function to pass to the above function:

asdf <- function(a, s, d, f){x <- c(a, s, d, f)}

Calling .Fortran("foo", asdf, vector(mode="numeric", length=22)) yields Error: invalid mode (closure) to pass to Fortran (arg 1) and passing "asdf" (as a string) results in a segfault, as the argument obviously doesn't fit the expected type (namely, a function).

FYI, I don't expect the code to do anything meaningful (that would be the task of another function), I mainly would like to know, whether passing functions (or function pointers) from R is possible at all or wether I better give up on this approach instantly and look for something that might work.

Thanks in advance,

Dean

like image 545
Sty Avatar asked Nov 04 '22 19:11

Sty


1 Answers

You can't pass R objects via .Fortran. You would need to use the .Call or .External interface to pass the R objects to C/C++ code.

You could write a C/C++ wrapper for your R function, which you could then call from your Fortran code (see Calling-C-from-FORTRAN-and-vice-versa in Writing R Extensions).

like image 152
Joshua Ulrich Avatar answered Nov 07 '22 21:11

Joshua Ulrich