由于不相关的原因,我需要将 C/C++ 函数名称传递给 Fortran 子例程,该子例程又调用该 C 函数。我发现我可以成功地将函数名传递到 Fortran 子例程中。在那个子程序中,我可以调用正确的 C 函数。但是,C 函数的参数在此调用中被破坏(当直接从 C 调用时,它工作正常)。我已经使用ISO C Binding来尝试让它工作,但无济于事。
这是一个MWE:
fortranRoutine.h:
extern "C" {
void fortranRoutine_(void(int status));
};
从Fortran.h调用:
void calledfromFortran(int status);
主.cpp:
#include "fortranRoutine.h"
#include "calledfromFortran.h"
using namespace std;
int main(int argc, char** argv) {
calledfromFortran(12);
fortranRoutine_(calledfromFortran);
return 0;
}
fortranRoutine.f90:
subroutine fortranRoutine(calledfromFortran)
use iso_c_binding
implicit none
interface
subroutine calledfromFortran(status) bind (c)
use iso_c_binding
integer(kind = c_int), intent(in) :: status
end subroutine calledfromFortran
end interface
integer(kind = c_int) :: one
one = 2
call calledfromFortran(one)
return
end subroutine fortranRoutine
从Fortran.cpp 调用:
#include <iostream>
#include "stdlib.h"
using namespace std;
void calledfromFortran(int status) {
cout << "In calledfromFortran:" << endl;
cout << " status: " << status << endl;
}
当前结果
当前运行它会给出:
In calledfromFortran:
status: 12
In calledfromFortran:
status: -1641758848
calledfromFortran
对from的第一次调用可以main
正常工作,但是从fortranRoutine
值调用它时会被破坏。请注意,每次运行时,后一个值都会发生变化。我究竟做错了什么?