无法将数组从FORTRAN传递到C.

我试图将一个维度数组从FORTRAN程序传递给C.

调用C函数,但它保存的值是垃圾。 但是如果我尝试使用整数变量调用相同的函数,我可以传递所需的值。 任何人都可以帮我解决这个问题吗?

我使用的代码与此类似

文件:fortran_prog.f

program test real*4 :: a(4) data a / 1,2,3,4 / call test_func(a) end program test 

文件:c_prog.c

 int test_func(double a[]) { int i; for(i=0;i<4;i++) { printf("%f\n",a[i]); } return 0; } 

在Fortran和C之间传递数组是一个非常重要的问题。 特定的C和Fortran编译器很重要。

我看到的第一个问题是你指定double来匹配real*4 。 这几乎在所有平台上都无效。 将C函数声明为:

 int test_func (float *a) 

这可能适用于某些平台,尽管许多Fortran编译器传递“数组描述符”的地址而不是数组本身。 查看Fortran编译器的文档。

 program test_Cfunc use iso_c_binding implicit none interface function test_func (a) bind (C, name="test_func") import integer (c_int) :: test_func real (c_double), dimension (1:4), intent (in) :: a end function test_func end interface real (c_double), dimension (1:4) :: a = [ 2.3, 3.4, 4.5, 5.6 ] integer (c_int) :: result result = test_func (a) write (*, *) result end program test_Cfunc 

使用Fortran的ISO C绑定,该解决方案可以移植到同一供应商的成对编译器,或Fortran编译器供应商支持的组合。 您不必了解特定编译器的传递约定,也不必处理Fortran编译器的name (由bindname子句覆盖)。 使用interface块描述Fortran的C例程,使用ISO C Binding中指定的Fortran类值指定C类型。 “内部模块”一章中的gfortran手册中列出了各种类型。 另请参阅“混合语言编程”一章。 由于ISO C Binding是语言标准的一部分,因此这个文档比gfortran更通用。