Fortran 中直接使用C进行混合编程

先上一个C写的函数 check_dir.c

   1: #ifndef CHECKDIR_H
   2: #define    CHECKDIR_H
   3:  
   4: #include <io.h>
   5:  
   6: #ifdef    __cplusplus
   7: extern "C" {
   8: #endif
   9:  
  10:     int checkdir_c_(char* dir)
  11:      {
  12:         if (_access(dir, 0) != -1)
  13:             return 0;
  14:         else
  15:             if (_mkdir(dir) == 0)
  16:             return 0;
  17:         else
  18:             return -1;
  19:     }
  20:  
  21: #ifdef    __cplusplus
  22: }
  23: #endif
  24:  
  25: #endif    /* CHECKDIR_H */

编译:gcc –c –o checkdir.o check_dir.c

在来一段fortran 调用的代码 iotils.f90

   1: subroutine checkdir(path)
   2:     implicit none
   3:  
   4:     character(len = 256) :: path, temp
   5:     integer(kind = 4) :: alive, checkdir_c
   6:  
   7:     temp = trim(path)//achar(0)
   8:     print *, "aa"//trim(temp)
   9:     alive = checkdir_c(trim(path))
  10:     if (alive /= 0) then
  11:         write(0,*) "error:文件夹"//trim(path)//"创建失败!"
  12:         stop
  13:     end if
  14: end subroutine checkdir

编译 gfortran –c –o iotils.o iotils.f90

主程序  test.f90

   1: program test
   2:     implict none
   3:     call checkdir("d:\a\b")
   4: end program test

编译 gfortran –c –o test.o test.f90

链接 gfortran –o test.exe test.o checkdir.o

 

大功告成

 

关键问题:

fortran编译器在编译的时候会自动在函数名后面加一个_,解决方法有两个:

1.给fortran 编译命令后面加一个编译参数,使之不自动产生下划线。

2.在c函数声明中后面加一个下划线,如checkdir_c_,而在fortran调用的时候采用 checkdir_c的形式来调用。

posted @ 2010-12-20 09:53  chillwind  阅读(617)  评论(0)    收藏  举报