从 C++ 调用带有可选参数的 Fortran 子例程

如何在使用可选参数的 C++ 标头中引用 Fortran 函数?对于每个可能的调用组合,我会在标题中放置一个原型吗?或者这甚至可能吗?

How would I reference a Fortran function in a C++ header that uses optional arguments? Would I have a prototype in the header for each possible combination of calls? Or is this even possible?

例如,Fortran:

For instance, Fortran:

subroutine foo(a, b, c) bind(c)
   real, intent(in), optional :: a, b, c
   ...
end subroutine foo

推荐答案

这是不可能的,至少是可移植的,除非你制作子程序 bind(C).

It is not possible, at least portably, unless you make the subroutine bind(C).

一旦你做了 bind(C),它只是传递一个在 C 端可以为 NULL 的指针.

Once you make it bind(C), it is just passing of a pointer which can be NULL on the C side.

subroutine foo(a, b, c) bind(C, name="foo")
   use iso_c_binding, only: c_float
   real(c_float), intent(in), optional :: a, b, c
   ...
end subroutine foo

(为了更好的可移植性,我使用了 iso_c_binding 模块中的 real(c_float) ,但这与这个问题有些相干)

(for greater portability I used real(c_float) from the iso_c_binding module, but that is somewhat tangential to this question)

在 C(++) 中

extern "C"{
  void foo(float *a, float *b, float *c);
}

foo(&local_a, NULL, NULL);

然后您可以创建一个调用 foo 并使用 C++ 样式可选参数的 C++ 函数.

and then you can make a C++ function which calls foo and which employs C++-style optional parameters.

Fortran 技术规范 ISO/IEC TS 29113:2012 中允许此功能用于 Fortran 与 C 的进一步互操作性,后来被合并到 Fortran 2018 中.

This capability was allowed in Fortran in Technical Specification ISO/IEC TS 29113:2012 on further interoperability of Fortran with C and was later incorporated into Fortran 2018.

相关文章