J3/01-395 Date: December 5, 2001 To: J3 From: /interop Subject: Enhanced C interoperability References: J3/01-381, WG5/N1442, J3/00-168 This paper is intended to document the thought process of /interop when considering WG5/N1442 and J3/01-381. /interop is not prepared to submit a proposal at this time, but sees merit in the requests in N1442. N1442 states: It is impossible for a Fortran procedure, while being called from C, to allocate an array and make that array available to the C code. Conversely, it is impossible for a C function, while being called from Fortran, to allocate an array and make that array available to the Fortran code. J3/00-168 attempts to resolve the former problem by introducing a new intrinsic that creates a Fortran pointer out of a C pointer. The latter problem can be solved by allowing C_LOC to take allocatable arrays as arguments. Richard Maine suggests that perhaps C_LOC should be allowed to take pointers as arguments as well. Subgroup is concerned about two issues: Memory leaks and aliasing. Subgroup believes that memory leaks can be addressed by a note admonishing the user to free any memory in C if the memory was allocated in C. This requires that the user keep track of memory allocated in C independent of its use through a Fortran pointer. Aliasing is a larger concern. To comply with Fortran rules, two fortran pointers that use the same C pointer (or overlapping pieces of memory obtained from C) should have the same type and kind. Further, if the address of a dummy argument is taken in a C routine then that dummy argument must have the TARGET attribute. Finally, subgroup B pointed out that section 16.8.6, items 17 and 18 reference association between variables of type C_PTR and targets; however, this form of association does not appear to be defined in the standard. The following is an outline of a possible solution to these issues. Edits are not included. - Enlarge pointer association to include variables of type C_PTR that are defined by the C_LOC intrinsic. - Allow BIND(C) on allocatable arrays and pointers. Such variables are interoperable with C. Thus C_LOC can be used on them. - Require that procedures defined by means other than fortran obey Fortran rules for aliasing. That is, the address of a dummy argument can be taken only if the argument has the target attribute. - Include the intrinsic CPTR_TO_FPTR (with a different name) as specified in the references. Require that pointers returned by that intrinsic obey Fortran aliasing rules. The concept of partial association should be helpful here.