Complex numbers

C has no complex numbers, but they are easy to simulate. To illustrate this, create a struct type containing two floating-point members of the correct size — two floatsfor the complex type, and two doublesfor the double complex type. The following creates the typedef COMPLEX:

typedef struct

{

float real; float imag; } COMPLEX;

Consider a program that consists of two source files:

The Fortran source file, which defines the main program unit

The C source file, which defines a function sqr_complex, having the following prototype declaration:

COMPLEX sqr_complex(COMPLEX cmx_val);

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 21 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.

112 Calling C routines from HP Fortran