Example 23 Example 8-3 sort_em.c

#include <stdio.h>

void BubbleSort(int a[], int size)

void BubbleSort(int a[], int size)

{

int i, j, temp;

for (i = 0; i < size - 1; i++) for (j = i + 1; j < size; j++) if (a[i] > a[j])

{

temp = a[i]; a[i] = a[j]; a[j] = temp;

}

}

Before a Fortran program can call this function correctly, it must resolve two issues:

1.The name of the C function contains both uppercase and lowercase letters.

2.The function expects its second argument (the size of the array) to be passed by value.

The following $HP$ ALIAS directive handles both issues:

!$HP$ ALIAS bubblesort = 'BubbleSort'(%REF,%VAL)

The name bubblesort is the alias that Fortran will use to refer to the C function, and the%REF and %VAL built-in functions change Fortran’s argument-passing conventions to conform to how the C function expects the arguments to be passed.

The following is an HP Fortran program that uses the $HP$ ALIAS directive to call the C function correctly.

Example 24 Example 8-4 test_sort.f90

PROGRAM main

!This program is linked with an object file that contains

!a C function with the following prototype declaration:

!void BubbleSort(int a[], int size);

!

!The ALIAS directive takes care of the differences

!between C and Fortran regarding case sensitivity

!and argument-passing conventions.

!$HP$ ALIAS bubblesort = 'BubbleSort'(%REF, %VAL) INTEGER, PARAMETER :: n = 10

INTEGER, DIMENSION(n) :: num=(/5,4,7,8,1,0,9,3,2,6/)

PRINT *, 'Before sorting: ', num CALL bubblesort(num, n)

PRINT *, 'After sorting: ', num END PROGRAM main

Here are the command lines to compile, link, and execute the program, followed by the output from a sample run:

$ cc -Aa -c sort_em.c

$ f90 test_sort.f90 sort_em.o $ a.out

Before sorting: 5 4 7 8 1 0 9 3 2 6

After sorting: 0 1 2 3 4 5 6 7 8 9

If you use the $HP$ ALIAS directive in many of the Fortran source files in your program, you may find it convenient to define all of the directives in one file and include that file in all of the Fortran source files with the +pre_include=fileoption. This option takes one argument, file, which is

Case sensitivity 115

Page 115
Image 115
HP UX Fortran Software Example 23 Example 8-3 sortem.c, $HP$ Alias bubblesort = BubbleSort%REF,%VAL, Case sensitivity