gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:35:24 25 4
gpt4 key购买 nike

如何在使用可选参数的 C++ header 中引用 Fortran 函数?我会在标题中为每种可能的调用组合提供一个原型(prototype)吗?或者这甚至可能吗?

例如,Fortran:

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

最佳答案

这是不可能的,至少是可移植的,除非你创建子例程 bind(C)

一旦你让它成为 bind(C),它只是传递一个指针,在 C 端可以为 NULL。

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),但这与这个问题有些无关)

在 C(++) 中

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

foo(&local_a, NULL, NULL);

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

在关于 Fortran 与 C 的进一步互操作性的技术规范 ISO/IEC TS 29113:2012 中,Fortran 允许使用此功能,后来并入 Fortran 2018。

关于c++ - 从 C++ 调用带有可选参数的 Fortran 子例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40089567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com