【问题标题】:Calling C Code from FORTRAN从 FORTRAN 调用 C 代码
【发布时间】:2013-08-17 09:56:18
【问题描述】:

鉴于 Microsoft FORTRAN 5.1 和 Microsoft C/C++ 14.0,以及该版本 FORTRAN 附带的链接器(必须用于其他依赖项),我如何创建 C 函数并从 FORTRAN 应用程序调用它?

【问题讨论】:

    标签: c fortran


    【解决方案1】:

    MSDN 上有一篇文章,这里有示例代码:FORTRAN calls to C

    【讨论】:

      【解决方案2】:

      你有两个选择。
      1) 我可以举例说明

      福特兰

      program ftest
      use iso_c_bindings
      implicit none
      interface
      function saythis(a) ! should be subroutine if saythis returns void
      import :: c_ptr
      type(c_ptr), value :: a
      end function saythis
      end interface
      
      character(len=80), target :: str
      type(c_ptr) cstr
      integer :: r
      
      str='Hello World From Fortran' // C_NULL_CHAR
      cstr=c_loc(str(1:1))
      r=saythis(cstr)
      

      C/C++

      #ifdef __cpluscplus
      #include &ltl;cstdio>
      using namespace std;
      #else
      #inlcude <stdio.h>
      #endif
      
      #ifdef __GNUC__
      #define FORT(func) func ## _
      #else
      #define FORT(func) __stdcall func ## _
      #endif
      
      #ifdef __cpluscplus
      extern "C" {
      #endif
      __declspec(dllexport) int FORT(sayit)(char* c)
      {
      return printf("%s\n",c);
      }
      
      #ifdef __cpluscplus
      }
      #endif
      

      这适用于 gcc 工具链。您必须对 DLL 和 fortran 目标代码进行转储,以查看名称是否正确匹配。
      其他方式类似:

      //This is for gcc toolchain
      //you'll have to find the symbol conversion yourself
      //I think that Visual Studio converts fortran names
      //to ALL CAPS so instead of func => _func you'll need func => FUNC
      

      福特兰

      program ftest
      integer aa,bb,cc
      common/vari/aa,bb,cc
      
      aa=7
      bb=11
      cc=0
      call dosomething
      call dosomethingelse(aa,bb,cc)
      

      C/C++

      #ifdef __cplusplus
      extern "C" {
      #endif
      int _dosomething();
      int _dosomethingelse(int*,int*,int*); //all fortran is pass by reference
      struct { int aa,bb,cc; } vari;
      #ifdef __cplusplus
      }
      #endif
      
      //function def's go here
      //struct vari should be the same memory as common/vari block
      

      编译命令

      $>g++ -c ctest.c <br/>
      $>gfortran -c ftest.f90 <br/>
      $>gfortran *.o -lstdc++ -o test_prog <br/>
      

      希望对你有帮助

      【讨论】:

        【解决方案3】:

        迟到总比不到好。 我记得在 Visual Studio 1 中使用过 ms fortran 5.1。我不确定哪个 Visual Studio 14.0 相当于,但我认为它是相对较新的,而不是 13 岁。 我认为这种组合不是入门的,因为 5.1 是 Windows 3 的 16 位编译器。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多