C++如何称呼Fortran 77的公共块

How C++ call Fortran 77's common blocks

本文关键字:Fortran C++      更新时间:2023-10-16

我刚开始编程,我想在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(),该怎么办?

除了行/列的主要顺序问题(5x5矩阵在C代码中会出现转置)之外,也许您可以按以下方式进行(请参阅本教程中关于公共块的部分):

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

请注意,C中的2D数组以行为主,而在FORTRAN中,它们以列为主,因此您需要用一种或另一种语言切换数组索引。