If you don’t have much leeway on the Fortran side, then you will be limited by nonportable, compiler-specific options (aka processor-dependent) and you will have to follow the RTFM approach and consult your compiler provided “developer and language reference guide”, if available.
Separately, this may be for future reference, know the “canonical” way to interoperate will be using standard facilities - see below:
- Fortran code: KEEP IT SIMPLE and follow the good coding practices with explicit interfaces (say via
MODULE
s), useBIND(C)
clause, and employ interoperable types, etc. as you have noted.
module m
use, intrinsic :: iso_c_binding, only : c_int
contains
subroutine sub( x ) bind(C, name="sub")
! Argument list
integer(c_int), intent(in) :: x(:)
print *, "In Fortran sub: size(x) = ", size(x)
print *, x
return
end subroutine
end module
- C code: develop descriptor(s) using standard Fortran stipulated toolsets to more complicated data structures with Fortran-specific attributes; arrays of assumed-shape are one such example, as noted upthread. So the code in C can look like below. Note the bit of added verbosity but which then yields the needed descriptors. The Fortran standard and resources such as Modern Fortran Explained can provide you with more background on the descriptors and methods available to work with them.
#include "ISO_Fortran_binding.h"
extern void sub(CFI_cdesc_t *);
int main(void)
{
enum N { N = 3 };
int x[N];
int i;
CFI_CDESC_T(1) descriptor_to_x;
CFI_index_t ext[1];
for (int i=0; i<N; i++) x[i] = 42+i;
ext[0] = (CFI_index_t)N;
i = CFI_establish((CFI_cdesc_t *)&descriptor_to_x, x, CFI_attribute_other,
CFI_type_int, 0, (CFI_rank_t)1, ext);
sub((CFI_cdesc_t *)&descriptor_to_x );
return 0;
}
- Building and running such code using Intel Fortran and Microsoft C/C++ toolsets on Windows
C:\temp>ifort /free /standard-semantics -c m.f
Intel(R) Fortran Intel(R) 64 Compiler Classic for applications running on Intel(R) 64, Version 2021.9.0 Build 20230302_000000
Copyright (C) 1985-2023 Intel Corporation. All rights reserved.
C:\temp>cl /c /W3 /EHsc c.c
Microsoft (R) C/C++ Optimizing Compiler Version 19.34.31937 for x64
Copyright (C) Microsoft Corporation. All rights reserved.
c.c
C:\temp>link c.obj m.obj /subsystem:console /out:c.exe
Microsoft (R) Incremental Linker Version 14.34.31937.0
Copyright (C) Microsoft Corporation. All rights reserved.
C:\temp>c.exe
In Fortran sub: size(x) = 3
42 43 44
You can review a similar example but which involves an ALLOCATABLE
received argument on the Fortran side here.