HP Fortran Programmer's Guide (B3908-90031; September 2011)

Calling C routines from HP Fortran
Sharing data
Chapter 8202
The common block to be shared with a C function can contain more than one data item. To do so, the C
source file must declare a structure whose members match the data items in common. Any C function
needing access to an item in common uses the extern statement to declare a variable of the structure type.
The name of the variable is that of the common block. To access an individual data item, the function uses
the C notation for referencing members of a structure.
HP Fortran uses the same packing and alignment rules when laying out common blocks in memory that
HP C uses for structures. However, the programmer must be sure to declare the number, types, and sizes of
the structure members in the same order as they appear in the common block. Refer to Table on page 183
for the data type correspondences for both languages.
The following example program consists of two source files that contain the Fortran main program unit and
a C function called from Fortran. The main program unit specifies a common block having two
double-precision variables. It writes to one of the variables and calls the C function. The C function reads
the variable written by Fortran and writes to the other one. After the call returns, Fortran reads both
variables.
The following are examples of Fortran and C source files.
Example 8-10 shared_common.f90
PROGRAM main
! This program uses the common block to share data with
! the C function get_nlog. C uses a structure type to
! declare the same items in common.
REAL(KIND=8) :: num, nlog_of_num
COMMON /globals/num, nlog_of_num
! a header for the table that is printed by the following
! DO loop
PRINT *, 'Number Natural Log of Number'
PRINT *, '-------+-----------------------'
! At each iteration, write a value to the common block
! variable num, call the C function get_nlog, and
! print the contents of both common block variables
! to the screen.
DO num = 2.0, 10.0
CALL get_nlog()
PRINT 10, num, ‘|’, nlog_of_num
END DO
10 FORMAT(3X, F3.0, 2X, A, 8X, F5.2)
END PROGRAM main