HP Fortran Programmer's Guide (September 2007)
Calling C routines from HP Fortran
Data types
Chapter 8178
The main subprogram calls sqr_complex, passing in a complex number. The C function
squares the number and returns the result. There is no complex data type in C, but this
example uses C’s typedef feature to create one.
The Fortran source file for such a scenario is shown below in the example pass_complex.f90.
Example 8-1 pass_complex.f90
PROGRAM main
! This program passes a complex number to a C function
! that squares it and returns the result. The C
! function has the following declaration prototype:
!
! complex sqr_complex(complex cmx_val);
!
! "complex" is not an intrinsic type for C but it
! creates a typedef for one, using a struct.
COMPLEX :: result, cmx_num = (2.5, 3.5)
! We have to declare the C function because we’re calling it
! as a function rather than a subroutine. If we didn’t
! declare it, Fortran would use the implicit typing rules
! by default and assume from the name, sqr_complex, that it
! returns a real.
COMPLEX sqr_complex
PRINT *, 'C will square this complex number: ', cmx_num
! Use the %VAL built-in function to indicate that cmx_num
! is being passed by value, as C expects it to be, and
! and not by reference, as Fortran does by default
result = sqr_complex(%VAL(cmx_num))
PRINT *, 'The squared result is: ', result
END PROGRAM main
The following is the C source file.
Example 8-2 sqr_complex.c
#include <stdio.h>
/* simulate Fortran’s complex number */
typedef struct
{