Can you elaborate on this a little more? What exactly is it that invalidates the struct during the call?
He didn’t say during but after.
I think he’s referring to this note/example in the standard:
REAL, TARGET :: X(1000), B
INTERFACE
REAL FUNCTION CFUN(ARRAY) BIND(C, NAME="Cfun")
REAL ARRAY(:)
END FUNCTION
END INTERFACE
B = CFUN(X)
Cfun is a C function. Before or during the invocation of Cfun, the processor will create a C descriptor for the array x. On return from Cfun, that C descriptor will become undefined.
J3/24-007 Section 18.8 “Restriction on lifetimes”,
A C descriptor whose address is a formal parameter that corresponds to a Fortran dummy argument becomes undefined on return from a call to the function from Fortran. If the dummy argument does not have either the TARGET or ASYNCHRONOUS attribute, all C pointers to any part of the object described by the C descriptor become undefined on return from the call, and any further use of them is undefined behavior.
@jwmwalrus shared a perfect example.
In practice Fortran compilers use a dope vector to keep track of the array properties. As many compilers were created before the enhanced C interop was introduced, the native descriptors/dope vectors, differ from the ISO Fortran mandated one. In the example above, when CFUN() is called, a compiler might need to pack from the native descriptor to the CFI_cdesc_t struct. When CFUN returns, the struct would be invalidated. (Technically a Fortran compiler need not be implemented in a language from the C family at all.)
Ok, I think I understand. Basically, this looks like the same thing that occurs for a pure fortran implementation. Namely, the target attribute is required for the actual argument and for the dummy argument in the interface to ensure that a temporary copy is not used to associate the arguments by the compiler. Section 18.8 extends that same principle also to arrays referenced through the C interop features. Something new to me in this thread is that the target attribute also prevents an array with the save attribute from being moved by the compiler for various optimization and/or alignment reasons.
So to answer the original post, it looks like the original library must be modified (by adding the target attribute) in order for the NumPY view to be valid. Without that attribute, none of the possibilities of fortran pointers, C pointers, or NumPy views of that array (even with the save attribute) can be guaranteed to work.