Intel® Fortran Compiler Classic and Intel® Fortran Compiler Developer Guide and Reference

ID 767251
Date 3/31/2023
Public

A newer version of this document is available. Customers should click here to go to the newest version.

Document Table of Contents

Pointers

For interoperating with C pointers, the module ISO_C_BINDING contains the derived types C_PTR and C_FUNPTR, which are interoperable with C object and function type pointers, respectively.

These types, as well as certain procedures in the module, provide the mechanism for passing dynamic arrays between the two languages. Because its elements do not need to be contiguous in memory, a Fortran pointer target or assumed-shape array cannot be passed to C. However, you can pass an allocated allocatable array to C, and you can associate an array allocated in C with a Fortran pointer. Additionally, as shown in the following, you can convert a pointer in C format to one in Fortran format.

Fortran program example:

program demo_c_f_pointer
       use, intrinsic :: iso_c_binding
       implicit none
    
       interface
         function make_array(n_elements) bind(C)
           import ! Make iso_c_binding visible here
           type(C_PTR) :: make_array
           integer(C_INT), value, intent(IN) :: n_elements
         end function make_array
       end interface
    
       type(C_PTR) :: cptr_to_array
       integer(C_INT), pointer :: array(:) => NULL()
       integer, parameter :: n_elements = 3 ! Number of elements
    
       ! Call C function to create and populate an array
       cptr_to_array = make_array(n_elements)
       ! Convert to Fortran pointer to array of n_elements elements
       call C_F_POINTER (cptr_to_array, array, [n_elements])
       ! Print value
       print *, array
    
end program demo_c_f_pointer

C module example:

#include <stdlib.h>
int  *make_array(int n_elements) {
           int *parray;
           int i;
	parray = (int*) malloc(n_elements * sizeof(int));
	for (i = 0; i < n_elements; i++) {
		parray[i] = i+1;
	}
	return parray;
 }