2

I am working with both C++ and Fortran code. The C++ code needs to call a Fortran subroutine. One parameter of the Fortran subroutine has Fortran type complex.

The C++ code is in one file, and the Fortran code subroutine is in another file. I am using gcc and gfortran on a 64-bit GNU/Linux system.

Here is a snippet showing the Fortran subroutine declaration (and a few additional lines):

SUBROUTINE  minp (AMP,L,L2,FMINP,PHI)
   REAL*4 AMP( L ),FMINP( L )
   COMPLEX PHI( L )

In the C++ file, I understand that arguments passed to the Fortran code need to be passed by reference, and not by value. The Fortran subroutine is declared as a function in the C++ code (at the top of the source code file) using the extern keyword.

extern "C"
{
minp_ (float *amp, int &L, int &L2, float *fminp, complex *phi);

}

However, the last parameter of the function is a complex C array. How might it be possible to:

  1. Allocate memory for a complex array in C/C++ to be passed in as the phi argument?
  2. Pass the array as an argument to the Fortran subroutine in such a way that the memory can be used by the Fortran code?

1 Answer 1

5

For interfacing C (and C++ via extern C) and Fortran, I recommend using Fortran's ISO C Binding. It provides complex types, C_FLOAT_COMPLEX, C_DOUBLE_COMPLEX, and C_LONG_DOUBLE_COMPLEX, to match C's types. By using the ISO C Binding and writing a Fortran interface declaration to match the C code, you will instruct the Fortran compiler to match the calling conventions of the C compiler. If you use the complex type with the ISO C Binding, dealing with the array won't be any different from a float/double/long double array. The gfortran manual has examples in the Chapter Mixed-Language Programing and describes the types and intrinsic procedures of the ISO C Binding in the Chapter Intrinsic Modules.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, M.S.B. That is indeed a viable way to proceed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.