【问题标题】:How C++ call Fortran 77's common blocksC++ 如何调用 Fortran 77 的通用块
【发布时间】:2016-02-17 06:31:27
【问题描述】:

我是编程新手,我想在我的 C++ 代码中调用 Fortran 77 通用块。其实我看过一些和我类似的问答,但我不是很清楚......

这个公共块由另一个 Fortran 77 子程序定义。

示例代码是:

common.inc:

!test common block:
real delta(5,5)
common /test/ delta
!save /test/ delta  ! any differences if I comment this line?

tstfunc.f

subroutine tstfunc()
    implicit none
    include 'common.inc'
    integer i,j
    do i = 1, 5
        do j = 1, 5
            delta(i,j)=2
            if(i.ne.j) delta(i,j)=0
            write (*,*) delta(i,j)
        end do
    end do
end

tst01.cpp

#include <iostream>

extern "C"
{
    void tstfunc_();
};

void printmtrx(float (&a)[5][5]){
    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++){
            std::cout<<a[j][i]<<'\t';
            a[j][i]+=2;
        }
        std::cout<<std::endl;
    }
}

int main()
{
//start...
    tstfunc_();
    printmtrx(delta);//here i want to call delta and manipulate it. 
    return 0;
}

如果我想将delta(来自common.inc)传递给C++函数printmtrx(),我应该怎么做?

【问题讨论】:

  • 这取决于编译器。您使用哪些编译器?
  • 亲爱的@MSalters,我使用 gfortran 和 g++
  • 你不调用普通块。它们包含数据,而不是代码。 “我该怎么做?”不是一个可以理解的问题,也没有证据表明这里存在实际问题。您的问题尚不清楚。
  • 感谢@EJP 我更新了我的问题
  • 但不是你的标题,而且仍然没有任何问题的证据。

标签: c++ gcc fortran gfortran fortran-common-block


【解决方案1】:

除了行/列主要顺序问题(5x5 矩阵会在 C 代码中出现转置),也许您可​​以按如下方式进行(参见 tutorial 中的公共块部分):

tstfunc1.f

  subroutine tstfunc()
      implicit none
      real delta(5, 5)
      common /test/ delta
      integer i,j
      do i = 1, 5
          do j = 1, 5
              delta(i,j)=2
              if(i.ne.j) delta(i,j)=0
              write (*,*) delta(i,j)
          end do
      end do
  end

tst01.cc

#include <iostream>

extern "C" {
  void tstfunc_();
  extern struct{
    float data[5][5];
  } test_;
}

void printmtrx(float (&a)[5][5]){
    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++){
          std::cout << a[i][j] << '\t';
          a[i][j] += 2;
        }
        std::cout << std::endl;
    }
 }

int main()
{
  //start...
  tstfunc_();

  printmtrx(test_.data);//here i want to call delta and manipulate it. 
  return 0;
}

然后为了编译:

gfortran -c -o tstfunc1.o tstfunc1.f    
g++ -o tst tst01.cc tstfunc1.o -lgfortran

【讨论】:

    【解决方案2】:

    请注意,C 中的二维数组是 row-major,而在 FORTRAN 中它们是 column-major,因此您需要在一种语言或另一种语言中切换数组索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-07
      • 2013-06-27
      • 2015-11-19
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      • 2017-11-08
      • 2012-05-04
      相关资源
      最近更新 更多