R: Advantages of using a Fortran subroutine with .Call and C/C++ wrapper instead of .Fortran?

痞子三分冷 提交于 2019-12-03 04:53:35

There might be an advantage if you are working with a large dataset. .Call can be much faster because you are not copying the data each time you call the function. For the case described in this question, there will be no such advantage, because the R 2.15.1 release notes state

.C() and .Fortran() do less copying: arguments which are raw, logical, integer, real or complex vectors and are unnamed are not copied before the call, and (named or not) are not copied after the call. Lists are no longer copied (they are supposed to be used read-only in the C code).

Switching to .Call means you give up the convenience of the .Fortran interface. You'd pass SEXPs into the C code, do any checks/manipulation of the data using the (scary and not well-documented) R API, and then call a Fortran function from C. Anyone else working with your code will have to understand the R API and C/Fortran interop.

The R package dotCall64 could be an interesting alternative. It provides .C64() which is an enhanced version of the Foreign Function Interface, i.e., .C() and .Fortran().

The interface .C64() can be used to interface both Fortran and C/C++ code. It

  • has a similar usage as .C() and .Fortran()
  • provides a mechanism to avoid unnecessary copies of read-only and write-only arguments
  • supports long vectors (vectors with more then 2^31-1 elements)
  • supports 64-bit integer type arguments

Hence, one can avoid unnecessary copies of read-only arguments while avoiding the .Call() interface in combination with a C wrapper function.

Some links:

I am one of the authors of dotCall64 and spam.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!