1

Problem A: I need to make lots calls with slightly different input parameters to a Fortran function from C++.

! FORTRAN code
subroutine myFortranFunction(a,b,c,d)
integer, intent(in) :: a
integer, optional intent(in) :: b
character(len=*), optional, intent(in) :: c
logical, optional, intent(in) :: d

!body of code

end subroutine myFortranFunction

Declaration of external fortran function:

// FORTRAN function that modifies various global variables.
extern "C" void myFortranFunction(int*, int*); 

Passing parameters by reference is wholly inconvenient, because I have to declare a whole bunch of constant integers just so I can point to them. Therefore, I am writing a C++ function outside of the main() to bypass this problem.

Problem B: But doing so, I run into a segmentation fault if I call myFortranFunction from the C++ function:

Here is the properly functioning code:

// C++ code that makes a successful call to myFortranFunction.
int main()
{
    int a = 3;
    int b = 2;
    myFortranFunction(&a, &b);
    return 0;
}

Here is code that causes segmentation fault 11:

// C++ code that causes a segmentation fault.
void callMyFortranFunction(int a, int b, int myTag)
{
    myFortranFunction(&a, &b);
}

int main()
{
    callMyFortranFunction(3, 2, 0);
    return 0;
}

To my consternation, if I remove the third argument from callMyFortranFunction, it works as expected, and I can't understand what's going on:

// C++ code that surprisingly works correctly
void callMyFortranFunction(int a, int b)
{
    myFortranFunction(&a, &b);
}

int main()
{
    callMyFortranFunction(3, 2);
    return 0;
}

How do I properly create a wrapper function to call a Fortran function?

QuantumDot
  • 293
  • 1
  • 3
  • 10

0 Answers0