Fortran/Mixing languages

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Types[edit | edit source]

Fortran types map quite well to intrinsic types in other compiled languages. The following is a table of Fortran-to-C types:

 Fortran            C
 =======            =
 COMMON             extern struct
 INTEGER*1          signed char
 INTEGER*2          short
 INTEGER*4          long
 INTEGER*8          long long
 INTEGER            int
 REAL               float
 REAL*4             float
 REAL*8             double
 REAL*16            long double
 LOGICAL            int
 LOGICAL*n          char [n]
 CHARACTER*n        char [n]
 DOUBLE PRECISION   double
 COMPLEX            float [2]
 COMPLEX*8          float [2]
 COMPLEX*16         double [2]
 COMPLEX*32         long double [2]

Arrays[edit | edit source]

The layout of Fortran arrays in memory contrasts with arrays in C and many C-based languages. When iterating over contiguous array elements in C, the rightmost array subscript varies the fastest, while in Fortran, the leftmost array subscript varies the fastest. Hence the element following x(1,1) in contiguous memory is x(2,1), not x(1,2). Furthermore, the element sub-scripting in C starts at 0, while Fortran starts at 1 by default. An element in Fortran may be x(1), while the equivalent value in C code would be x[0]. However, when passing a Fortran array to a C function, you do not need to (and should not) reshape the array into C-style subscripts first; the compiler will automatically do this for you.

Global Storage[edit | edit source]

See the Common Blocks section.

Subroutine and function calls[edit | edit source]

Many languages push their arguments onto the stack, some as constants and some as addresses. In most compilers, Fortran will compile a block of pointers to variables and constants, and push the address of that block. So, if we had a Fortran procedure defined as follows:

subroutine my_sub(i, j, x)

then the C definition would be:

struct my_sub_args {
    int *i;
    int *j;
    float *x;
} my_sub_args = {&i, &j, &x};
void my_sub(my_sub_args*);

The C code could call the routine as follows:

my_sub(&my_sub_args);

The PL/1 Special Case[edit | edit source]

In PL/1, you can define an external common block, subroutine, or procedure to be of type FORTRAN. When you do this, everything, down to subscript order, will be handled for you. Likewise, you can define a PL/1 item, such as a subroutine, to be of type FORTRAN, and it will then be callable by Fortran using Fortran's calling conventions.