R:使用带有.Call和C / C ++包装器的Fortran子程序代替.Fortran的优点? [英] R: Advantages of using a Fortran subroutine with .Call and C/C++ wrapper instead of .Fortran?

查看:157
本文介绍了R:使用带有.Call和C / C ++包装器的Fortran子程序代替.Fortran的优点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个R包,它使用大量的Fortran子例程来递归线性代数计算的嵌套循环(主要取决于BLAS和LAPACK例程)。作为Fortran的接口,我使用 .Fortran 函数。我刚刚阅读了 Jonathan Callahan的博文,关于使用 .Call 而不是在使用C / C ++编写的子程序时, .C ,它让我想到使用 .Call 接口也使用Fortran子例程时,通过在C中编写一个简单的包装器,然后调用Fortran子例程?



如上所述,我的Fortran代码非常简单感觉我只是玩双维或整数类型的多维数组。但我了解到,我必须在R端编写相当多的检查来确保一切都不会因为我不小心忘记将某些矩阵的存储模式更改为整数或某些矩阵的维度发生变化而崩溃。 / p>

子程序写成F90 / 95。 可能有如果您正在处理大型数据集,则具有优势。 。呼叫可以更快,因为每次调用该函数时都不复制数据。对于这个问题中描述的情况,将不会有这样的优势,因为R 2.15.1发行说明指出了


.C()和.Fortran()少复制:在调用之前不会复制原始,逻辑,整型,实型或复型向量和未命名的参数,并且在调用之后不会复制(named或not)参数。不再复制列表(它们应该在C代码中以只读方式使用)。


切换到.Call意味着您放弃.Fortran界面的便利。您将SEXP传递到C代码中,使用(可怕且没有很好记录的)R API对数据进行任何检查/操作,然后从C中调用Fortran函数。任何使用您的代码的人都必须了解R API和C / Fortran互操作。

I have an R package which uses lots of Fortran subroutines for nested loops of recursive linear algebra computations (depending heavily on BLAS and LAPACK routines). As an interface to Fortran, I use .Fortran function. I just read Jonathan Callahan's blog post about using .Call instead of .C in case of subroutines written in C/C++, and it got me thinking that would it be better to use .Call interface also when using Fortran subroutines, by writing a simple wrapper in C which then calls the Fortran subroutines?

As said, my Fortran codes are quite simple in a sense that I just play with multidimensional arrays of type double or integer. But I have learned that I must write quite a lot of checks in R side to ensure that everything doesn't crash because of I accidentally forgot to change the storage mode of some matrix to integer or the dimensions of some matrix were changed etc.

Subroutines are written as F90/95.

解决方案

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.

这篇关于R:使用带有.Call和C / C ++包装器的Fortran子程序代替.Fortran的优点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆