-1

我是编程新手,我想在我的 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(),我该怎么办?

4

2 回答 2

1

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

于 2015-11-16T08:43:10.920 回答
1

除了行/列主要顺序问题(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
于 2015-11-16T08:45:01.970 回答