Calling C Pointer-type Function from Fortran

In Intel® Fortran, the result of a C pointer-type function is passed by reference as an additional, hidden argument. The function on the C side needs to emulate this as follows:

Calling C Pointer Function from Fortran

Fortran code
program test
interface
function cpfun()
integer, pointer:: cpfun
end function
end interface
integer, pointer:: ptr
ptr => cpfun()
print*, ptr
end

C Code
#include <malloc.h>
void *cpfun_(int **LP)
{
*LP = (int *)malloc(sizeof(int));
**LP = 1;
return LP;
}

The function’s result (int *) is returned as a pointer to a pointer (int **), and the C function must be of type void (not int*). The hidden argument comes at the end of the argument list, if there are other arguments, and after the hidden lengths of any character arguments.

In addition to pointer-type functions, the same mechanism should be used for Fortran functions of user-defined type, since they are also returned by reference as a hidden argument. The same is true for functions returning a derived type (structure) or character if the function is character*(*).

Note
Calling conventions such as these are implementation-dependent and are not covered by any language standards. Code that is using them may not be portable.