我是编程新手,我想在我的C ++代码中调用Fortran 77公共块。其实我读过一些与我类似的Q& A,但我不太清楚......
此公共块由另一个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()
,我该怎么办?
答案 0 :(得分:1)
请注意,C中的2D数组是row-major,而在FORTRAN中它们是column-major,因此您需要使用一种语言或另一种语言切换数组索引。
答案 1 :(得分: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