For reasons that are not relevant, I need to pass a C/C++ function name into a Fortran subroutine, which, in turn, calls that C function. What I have found is that I can succesfully pass the function name into the Fortran subroutine. In that subroutine I can call the correct C function. However, the arguments of the C function get broken on this call (when called directly from C it works fine). I have used ISO C Binding to try and get this to work, to no avail.
Here is a MWE:
fortranRoutine.h:
extern "C" {
void fortranRoutine_(void(int status));
};
calledfromFortran.h:
void calledfromFortran(int status);
main.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
calledfromFortran.cpp:
#include <iostream>
#include "stdlib.h"
using namespace std;
void calledfromFortran(int status) {
cout << "In calledfromFortran:" << endl;
cout << " status: " << status << endl;
}
Current results
Running this currently gives:
In calledfromFortran:
status: 12
In calledfromFortran:
status: -1641758848
The first call to calledfromFortran from main works correctly, but when it’s called from fortranRoutine the value is broken. Note, each time it’s run that latter value changes. What am I doing wrong?
When passing scalar values between Fortran and C, you have basically two options:
You pass them by reference: On the C-side you have to make sure, that you use pointers to those scalars.
You pass them by value: On the Fortran side you have to make sure that you use the
VALUEattribute, as already suggested by other posts.As for the
intent(in)attribute, it can stay there, as it does not affect, whether the variable is passed by value or reference. In Fortran, arguments are always passed by reference unless you specify theVALUEattribute. The attributeintent(in)only tells the compiler to prevent a usage of that dummy argument in the routine, which would change its value.Additional note on the naming: You should specify your Fortran routine
fortranRoutinealso withbind(c). This way you can specify its name as seen from C, even if it is inside a module:This way you can be sure, the name of the function to be called from C is
fortranroutine, independent of the convention of the compiler to append underscores, prepend module names or convert names to lower case. Consequently, you would have a a header file in C, which should work compiler independently: