Fortran Programming Guide | ![]() ![]() ![]() ![]() ![]() |
C-Fortran Interface
This chapter treats issues regarding Fortran and C interoperability.
The discussion is inherently limited to the specifics of the Sun FORTRAN 77, Fortran 95, and C compilers.
Note Material common to both FORTRAN 77 and Fortran 95 is presented in examples that use FORTRAN 77.
Compatibility Issues
Most C-Fortran interfaces must agree in all of these aspects:
- Function/subroutine: definition and call
- Data types: compatibility of types
- Arguments: passing by reference or value
- Arguments: order
- Procedure name: uppercase and lowercase and trailing underscore (_)
- Libraries: telling the linker to use Fortran libraries
Some C-Fortran interfaces must also agree on:
- Arrays: indexing and order
- File descriptors and
stdio
- File permissions
Function or Subroutine?
The word function has different meanings in C and Fortran. Depending on the situation, the choice is important:
- In C, all subprograms are functions; however, some may return a null (void) value.
- In Fortran, a function passes a return value, but a subroutine does not.
When a Fortran routine calls a C function:
- If the called C function returns a value, call it from Fortran as a function.
- If the called C function does not return a value, call it as a subroutine.
When a C function calls a Fortran subprogram:
- If the called Fortran subprogram is a function, call it from C as a function that returns a compatible data type.
- If the called Fortran subprogram is a subroutine, call it from C as a function that returns a value of
int
(compatible to FortranINTEGER*4
) orvoid
. A value is returned if the Fortran subroutine uses alternate returns, in which case it is the value of the expression on theRETURN
statement. If no expression appears on theRETURN
statement, and alternate returns are declared onSUBROUTINE
statement, a zero is returned.Data Type Compatibility
The tables below summarize the data sizes and default alignments for FORTRAN 77 and Fortran 95 data types. In both tables, note the following:
- C data types
int
,long
int
, andlong
are equivalent (4 bytes). In a 64-bit environment and compiling with-xarch=v9
orv9a
,long
and pointers are 8 bytes. This is referred to as "LP64".REAL*16
andCOMPLEX*32
, (REAL(KIND=16)
andCOMPLEX(KIND=16)
), are available only on SPARC platforms. In a 64-bit environment and compiling with-xarch=v9
orv9a
, alignment is on 16-byte boundaries.- Alignments marked 4/8 for SPARC indicate that alignment is 8-bytes by default, but on 4-byte boundaries in COMMON blocks. The maximum alignment in COMMON is 4-bytes.
- The elements and fields of arrays and structures must be compatible.
- You cannot pass arrays, character strings, or structures by value.
- You can pass arguments by value from
f77
to C, but not from C tof77
, since%VAL()
is not allowed in a Fortran dummy argument list.FORTRAN 77 and C Data Types
TABLE 11-1 shows the sizes and allowable alignments for FORTRAN 77 data types. It assumes no compilation options affecting alignment or promoting default data sizes are applied. (See also the FORTRAN 77 Language Reference Manual).
SPARC: Fortran 95 and C Data Types
The following table similarly compares the Fortran 95 data types with C.
Case Sensitivity
C and Fortran take opposite perspectives on case sensitivity:
- C is case sensitive--case matters.
- Fortran ignores case.
The
f77
andf95
default is to ignore case by converting subprogram names to lowercase. It converts all uppercase letters to lowercase letters, except within character-string constants.There are two usual solutions to the uppercase/lowercase problem:
- In the C subprogram, make the name of the C function all lowercase.
- Compile the Fortran program with the
-U
option, which tells the compiler to preserve existing uppercase/lowercase distinctions on function/subprogram names.Use one of these two solutions, but not both.
Most examples in this chapter use all lowercase letters for the name in the C function, and do not use the
f95
orf77
-U
compiler option.Underscores in Routine Names
The Fortran compiler normally appends an underscore (
_
) to the names of subprograms appearing both at entry point definition and in calls. This convention differs from C procedures or external variables with the same user-assigned name. All Fortran library procedure names have double leading underscores to reduce clashes with user-assigned subroutine names.There are three usual solutions to the underscore problem:
- In the C function, change the name of the function by appending an underscore to that name.
- Use the
C()
pragma to tell the Fortran compiler to omit those trailing underscores.- Use the
f77
andf95
-ext_names
option to compile references to external names without underscores.Use only one of these solutions.
The examples in this chapter could use the
C()
compiler pragma to avoid underscores. TheC()
pragma directive takes the names of external functions as arguments. It specifies that these functions are written in the C language, so the Fortran compiler does not append an underscore as it ordinarily does with external names. TheC()
directive for a particular function must appear before the first reference to that function. It must also appear in each subprogram that contains such a reference. The conventional usage is:
EXTERNAL ABC, XYZ !$PRAGMA C( ABC, XYZ )If you use this pragma, the C function does not need an underscore appended to the function name. (Pragma directives are described in the Fortran User's Guide.)
Argument-Passing by Reference or Value
In general, Fortran routines pass arguments by reference. In a call, if you enclose an argument with the
f77
andf95
nonstandard function%VAL()
, the calling routine passes it by value.In general, C passes arguments by value. If you precede an argument by the ampersand operator (
&
), C passes the argument by reference using a pointer. C always passes arrays and character strings by reference.Argument Order
Except for arguments that are character strings, Fortran and C pass arguments in the same order. However, for every argument of character type, the Fortran routine passes an additional argument giving the length of the string. These are
long
int
quantities in C, passed by value.
- Address for each argument (datum or function)
- A
long
int
for each character argument (the whole list of string lengths comes after the whole list of other arguments)Example:
CHARACTER*7 S
INTEGER B(3)
...
CALL SAM( S, B(2) ) char s[7];
int b[3];
...
sam_( s, &b[1], 7L ) ;Array Indexing and Order
Array indexing and order differ between Fortran and C.
Array Indexing
C arrays always start at zero, but by default Fortran arrays start at 1. There are two usual ways of approaching indexing.
- You can use the Fortran default, as in the preceding example. Then the Fortran element
B(2)
is equivalent to the C elementb[1]
.- You can specify that the Fortran array B starts at B(0) as follows:
INTEGER B(0:2)
- This way, the Fortran element
B(1)
is equivalent to the C elementb[1]
.Array Order
Fortran arrays are stored in column-major order:
A(3,2)
A(1,1) A(2,1) A(3,1) A(1,2) A(2,2) A(3,2)C arrays in row-major order:
A[3][2]
A[0][0] A[0][1] A[1][0] A[1][1] A[2][0] A[2][1]For one-dimensional arrays, this is no problem. For two-dimensional and higher arrays, be aware of how subscripts appear and are used in all references and declarations--some adjustments might be necessary.
For example, it may be confusing to do part of a matrix manipulation in C and the rest in Fortran. It might be preferable to pass an entire array to a routine in the other language and perform all the matrix manipulation in that routine to avoid doing part in C and part in Fortran.
File Descriptors and
stdio
Fortran I/O channels are in terms of unit numbers. The I/O system does not deal with unit numbers but with file descriptors. The Fortran runtime system translates from one to the other, so most Fortran programs do not have to recognize file descriptors.
Many C programs use a set of subroutines, called standard I/O (or
stdio
). Many functions of Fortran I/O use standard I/O, which in turn uses operating system I/O calls. Some of the characteristics of these I/O systems are listed in in the following table.
File Permissions
C programs typically open input files for reading and output files for writing or for reading and writing. A
f77
program canOPEN
a fileREADONLY
or withREADWRITE='READ'
or'WRITE'
or'READWRITE'
.f95
supports theREADWRITE
specifier, but notREADONLY
.Fortran tries to open a file with the maximum permissions possible, first for both reading and writing, then for each separately.
This event occurs transparently and is of concern only if you try to perform a READ, WRITE, or ENDFILE operation but you do not have permission. Magnetic tape operations are an exception to this general freedom, since you can have write permissions on a file, but not have a write ring on the tape.
Libraries and Linking With the
f77
orf95
CommandTo link the proper Fortran and C libraries, use the
f77
orf95
command to invoke the linker.Example 1: Use
f77
to link:
demo%cc -c someCroutine.c
demo%f95 theF95routine.f someCroutine.o
The linking step
demo%a.out
4.0 4.58.0 9.0demo%Fortran Initialization Routines
Main programs compiled by
f77
andf95
call dummy initialization routinesf77_init
orf90_init
in the library at program start up. The routines in the library are dummies that do nothing. The calls the compilers generate pass pointers to the program's arguments and environment. These calls provide software hooks the programmer can use to supply their own routines, in C, to initialize their program in any customized manner before the program starts up.One possible use of these initialization routines to call
setlocale
for an internationalized Fortran program. Becausesetlocale
does not work iflibc
is statically linked, only Fortran programs that are dynamically linked withlibc
should be internationalized.The source code for the
init
routines in the library is
void f77_init(int *argc_ptr, char ***argv_ptr, char ***envp_ptr) {}void f90_init(int *argc_ptr, char ***argv_ptr, Char ***envp_ptr) {}The routine
f77_init
is called byf77
main programs. The routinef90_init
is called byf95
main programs. The arguments are set to the address ofargc
, the address ofargv
, and the address ofenvp
.Passing Data Arguments by Reference
The standard method for passing data between Fortran routines and C procedures is by reference. To a C procedure, a Fortran subroutine or function call looks like a procedure call with all arguments represented by pointers. The only peculiarity is the way Fortran handles character strings and functions as arguments and as the return value from a CHARACTER*n function.
Simple Data Types
For simple data types (not COMPLEX or CHARACTER strings), define or pass each associated argument in the C routine as a pointer:
COMPLEX Data
Pass a Fortran COMPLEX data item as a pointer to a C struct of two float or two double data types:
In 64-bit environments and compiling with
-xarch=v9
,COMPLEX
values are returned in registers.Character Strings
Passing strings between C and Fortran routines is not recommended because there is no standard interface. However, note the following:
- All C strings are passed by reference.
- Fortran calls pass an additional argument for every argument with character type in the argument list. The extra argument gives the length of the string and is equivalent to a C long int passed by value. (This is implementation dependent.) The extra string-length arguments appear after the explicit arguments in the call.
A Fortran call with a character string argument is shown in the next example with its C equivalent:
TABLE 11-6 Passing a CHARACTER string CHARACTER*7 S
INTEGER B(3)
...
CALL CSTRNG( S, B(2) )
...char s[7];
int b[3];
...
cstrng_( s, &b[1], 7L );
...
If the length of the string is not needed in the called routine, the extra arguments may be ignored. However, note that Fortran does not automatically terminate strings with the explicit null character that C expects. This must be added by the calling program.
One-Dimensional Arrays
Array subscripts in C start with 0.
Two-Dimensional Arrays
Rows and columns between C and Fortran are switched.
Structures
C and FORTRAN 77 structures and Fortran 95 derived types can be passed to each other's routines as long as the corresponding elements are compatible.
Pointers
A FORTRAN 77 pointer can be passed to a C routine as a pointer to a pointer because the Fortran routine passes arguments by reference.
C pointers are compatible with Fortran 95 scalar pointers, but not array pointers.
Passing Data Arguments by Value
Call by value is available only for simple data with FORTRAN 77, and only by Fortran routines calling C routines. There is no way for a C routine to call a Fortran routine and pass arguments by value. It is not possible to pass arrays, character strings, or structures by value. These are best passed by reference.
Use the nonstandard Fortran function
%VAL(
arg)
as an argument in the call.In the following example, the Fortran routine passes x by value and y by reference. The C routine incremented both x and y, but only y is changed.
Functions That Return a Value
A Fortran function that returns a value of type BYTE (FORTRAN 77 only), INTEGER, REAL, LOGICAL, DOUBLE PRECISION, or REAL*16 (SPARC only) is equivalent to a C function that returns a compatible type (see TABLE 11-1 and TABLE 11-2). There are two extra arguments for the return values of character functions, and one extra argument for the return values of complex functions.
Returning a Simple Data Type
The following example returns a REAL or float value. BYTE, INTEGER, LOGICAL, DOUBLE PRECISION, and REAL*16 are treated in a similar way:
Returning COMPLEX Data
A Fortran function returning COMPLEX or DOUBLE COMPLEX on SPARC V8 platforms is equivalent to a C function with an additional first argument that points to the return value in memory. The general pattern for the Fortran function and its corresponding C function is:
COMPLEX FUNCTION CF(
a1, a2, ..., an)cf_ (
return, a1, a2, ..., an)struct { float r, i; } *
return
In 64-bit environments and compiling with
-xarch=v9
,COMPLEX
values are returned in floating-point registers:COMPLEX
andDOUBLE
COMPLEX
in%f0
and%f1
, andCOMPLEX*32
in%f0
,%f1
,%f2
, and%f3
. These registers are not directly accessible to C programs, preventing such interoperability between Fortran and C on SPARC V9 platforms for this case.Returning a CHARACTER String
Passing strings between C and Fortran routines is not encouraged. However, a Fortran character-string-valued function is equivalent to a C function with two additional first arguments--data address and string length. The general pattern for the Fortran function and its corresponding C function is:
CHARACTER*
nFUNCTION C(
a1, ..., an)void c_ (
result, length, a1, ..., an)
result
char[ ];
long length;
Here is an example:
In this example, the C function and calling C routine must accommodate two initial extra arguments (a pointer to the result string and the length of the string) and one additional argument at the end of the list (length of character argument). Note that in the Fortran routine called from C, it is necessary to explicitly add a final null character.
Labeled COMMON
Fortran labeled COMMON can be emulated in C by using a global
struct
.
TABLE 11-16 Emulating Labeled COMMON COMMON /BLOCK/ ALPHA,NUM
...extern struct block {
float alpha;
int num;
};
extern struct block block_ ;
main ()
{
...
block_.alpha = 32.;
block_.num += 1;
...
}
Note that the external name established by the C routine must end in an underscore to link with the block created by the Fortran program. Note also that the C directive
#pragma
pack
may be needed to get the same padding as with Fortran. Bothf77
andf95
align data in COMMON blocks to at most 4-byte boundaries.Sharing I/O Between Fortran and C
Mixing Fortran I/O with C I/O (issuing I/O calls from both C and Fortran routines) is not recommended. It is better to do all Fortran I/O or all C I/O, not both.
The Fortran I/O library is implemented largely on top of the C standard I/O library. Every open unit in a Fortran program has an associated standard I/O file structure. For the
stdin
,stdout
, andstderr
streams, the file structure need not be explicitly referenced, so it is possible to share them.If a Fortran main program calls C to do I/O, the Fortran I/O library must be initialized at program startup to connect units 0, 5, and 6 to
stderr
,stdin
, andstdout
, respectively. The C function must take the Fortran I/O environment into consideration to perform I/O on open file descriptors.However, if a C main program calls a Fortran subprogram to do I/O, the automatic initialization of the Fortran I/O library to connect units 0, 5, and 6 to
stderr
,stdin
, andstdout
is lacking. This connection is normally made by a Fortran main program. If a Fortran function attempts to reference thestderr
stream (unit 0) without the normal Fortran main program I/O initialization, output will be written tofort.0
instead of to thestderr
stream.The C main program can initialize Fortran I/O and establish the preconnection of units 0, 5, and 6 by calling the
f_init()
FORTRAN 77 library routine at the start of the program and, optionally,f_exit()
at termination.Remember: even though the main program is in C, you should link with
f77
.Alternate Returns
Fortran's alternate returns mechanism is obsolescent and should not be used if portability is an issue. There is no equivalent in C to alternate returns, so the only concern would be for a C routine calling a Fortran routine with alternate returns.
The Sun Fortran implementation returns the int value of the expression on the RETURN statement. This is implementation dependent and its use should be avoided.
Sun Microsystems, Inc. Copyright information. All rights reserved. Feedback |
Library | Contents | Previous | Next | Index |