从C包装程序调用FORTRAN函数

问题描述 投票:2回答:1

我是这的新手,但是我需要从C访问一些旧的Fortran 77函数。我不想在可能的情况下更改Fortran代码,我真的更愿意编写一个包装程序以从C调用Fortran函数。我希望得到一个最小的工作示例(在Linux上)。我做了什么:

在somefunction.f文件中:

REAL*8 FUNCTION MYFUNC(ZZ)
      IMPLICIT NONE
      REAL*8 ZZ, T1
      T1 = ZZ + 1.0D0
      MYFUNC = T1
      RETURN
      END

gfortran -c somefunction.f -o somefunction.o编译。

在文件debug.c中:

#include <stdio.h>

double cfunc(double x) {
    double result = myfunc_( &x );
    return result;
}
int main() {
    double test = cfunc(3.0);
    printf(" %.15f ",test);
}

gcc -c debug.c -o debug.o编译。

然后我给出gcc debug.o somefunction.o./a.out

但是,我得到的数字不是3 + 1 = 4。我该如何纠正?


P.S:如果解决了,我的实际功能会稍微复杂一些:

  1. 如果要用MYFUNC代替类型COMPLEX*16 FUNCTION MYFUNC(ZZ)且ZZ也很复杂,该怎么办?

  2. 如果MYFUNC调用某些内置的Fortran函数,例如CDLOG(ZZ),该怎么办?

  3. 如果访问一个公共块怎么办?也可以容纳吗?

c fortran fortran77
1个回答
0
投票

好,仅供参考,正如@IanBush所说,C程序应该已经声明了myfunc的返回类型,

#include <stdio.h>

double myfunc_(double*);

double cfunc(double x) {
    double result = myfunc_( &x );
    return result;
}
int main() {
     double test = cfunc(3.0);
     printf(" %.15f ",test);
}
© www.soinside.com 2019 - 2024. All rights reserved.