简体   繁体   English

从 C++ 调用 Fortran 有多“昂贵”?

[英]How "expensive" is it to call Fortran from C++?

I'm writting a program in C++ that calls some functions I had written in Fortran.我正在用 C++ 编写一个程序,它调用我用 Fortran 编写的一些函数。 I was going to test a very basic example in which I call a function called toRadians from the C++ code:我将测试一个非常基本的示例,在该示例中,我从 C++ 代码中调用了一个名为 toRadians 的函数:

real function toRadian(degree)
  implicit none

  real, intent(in) :: degree
  real :: radians

  radians = (degree*PI)/180
  return
end function toRadian

And so I wonder, is this "worth it"?所以我想知道,这“值得”吗? When I finish the whole thing that function will be called within Fortran where the bulk of the computations will be done, but doing this basic example got me thinking about if, for a simple computation like this, is calling the Fortran function more expensive than just having that function in C++?当我完成整个事情时,该函数将在 Fortran 中调用,其中大部分计算将完成,但是做这个基本示例让我思考,对于这样的简单计算,调用 Fortran 函数是否比仅仅调用更昂贵在 C++ 中有那个函数?

Sorry for my ignorance I'm not very sure about how the linking between these compiled codes works.抱歉我的无知,我不太确定这些编译代码之间的链接是如何工作的。 (I'm also very new with Fortran so if you want to make any remark about the previous function please go ahead). (我对 Fortran 也很新,所以如果你想对以前的功能发表任何评论,请继续)。

Thanks for your time and have a nice day.感谢您的时间,祝您有美好的一天。

Calling a Fortran function is as cheap as calling another C++ function.调用 Fortran 函数与调用另一个 C++ 函数一样便宜。 Usually.通常。

The problem is the compatibility between the two languages.问题是两种语言之间的兼容性。 The best way to start this in Fortran is to use iso_c_binding so that the function has a C calling convention.在 Fortran 中启动此操作的最佳方法是使用iso_c_binding以便函数具有 C 调用约定。

Then the other issue is that both languages require their own runtime libraries, and there are no linker flag to use both.然后另一个问题是两种语言都需要自己的运行时库,并且没有链接器标志可以同时使用这两种语言。 So the usual practice is to create a shared library for the Fortran code and link it against the C++ application (and vice-versa when it's calling C++ from Fortran).因此,通常的做法是为 Fortran 代码创建一个共享库并将其链接到 C++ 应用程序(反之亦然,当它从 Fortran 调用 C++ 时)。

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

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