繁体   English   中英

编写调用Fortran库的R包

[英]Writing R package that call Fortran library

我正在尝试编写一个调用Fortran子例程的R包。 我正在使用Rstudio包模板自动创建一堆文件和目录。

./R/我有一个文件,Fpi.R

Fpi <- function(DARTS, ROUNDS) {
  if (!is.loaded('Fpi')) {
    dyn.load("./src/Fpi.so")
  }
  retvals <- .Fortran("pi", avepi = as.numeric(1), DARTS =  as.integer(DARTS), ROUNDS =  as.integer(ROUNDS))
  return(retvals$avepi)
}

./src/我有Fpi.f90

subroutine dboard(darts, dartsscore)
  implicit none
  integer, intent(in)           :: darts
  double precision, intent(out) :: dartsscore
  double precision              :: x_coord, y_coord
  integer                       :: score, n

score = 0
do n = 1, darts
  call random_number(x_coord)
  call random_number(y_coord)

  if ((x_coord**2 + y_coord**2) <= 1.0d0) then
  score = score + 1
  end if
end do

dartsscore = 4.0d0*score/darts

end subroutine dboard

subroutine pi(avepi, DARTS, ROUNDS)
  implicit none
  double precision, intent(out)   ::  avepi
  integer, intent(in)             ::  DARTS, ROUNDS
  integer                         ::  MASTER, rank, i, n
  integer, allocatable            ::  seed(:)
  double precision                ::  pi_est, homepi, pirecv, pisum

interface 
   subroutine dboard(darts, dartsscore)
      implicit none
      integer, intent(in)           :: darts
      double precision, intent(out) :: dartsscore
   end subroutine dboard
end interface

! we set it to zero in the sequential run
rank = 0
! initialize the random number generator
! we make sure the seed is different for each task
call random_seed()
call random_seed(size = n)
allocate(seed(n))
seed = 12 + rank*11
call random_seed(put=seed(1:n))
deallocate(seed)

avepi = 0
do i = 0, ROUNDS-1
  call dboard(darts, pi_est)
  ! calculate the average value of pi over all iterations
  avepi = ((avepi*i) + pi_est)/(i + 1)
end do
end subroutine pi

我还有rstudio生成的通用DESCRIPTION和NAMESPACE文件。

我可以构建和加载库,但当我尝试使用它时,我收到此错误:

> library(MyPi)
> Fpi(DARTS = 100, ROUNDS = 100)
Error in .Fortran("pi", avepi = as.numeric(1), DARTS = as.integer(DARTS),  : 
  "pi" not resolved from current namespace (MyPi)

我怎样才能解决这个问题? 谢谢!

我只需要为我的NAMESPACE添加一行

useDynLib(Fpi)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM