c_loc -> c_ptr -> c_f_pointer round trip

Jeffrey Whitaker whitaker.jeffrey@gmail.com
Fri Apr 28 17:39:00 GMT 2017


On Fri, Apr 28, 2017 at 11:25 AM, Damian Rouson
<damian@sourceryinstitute.org> wrote:
>
>
> On April 24, 2017 at 3:23:42 PM, Jeffrey Whitaker (whitaker.jeffrey@gmail.com(mailto:whitaker.jeffrey@gmail.com)) wrote:
>
>> Hi: My use case is as follows. 1) create a non-interoperable fortran
>> derived type pointer (e.g. with allocatable components), then create
>> an opaque handle by passing it to c_loc,
>
> The committee draft of the Fortran 2015 standard includes the following
>
> Note 18.5
>
> "Where the actual argument is of noninteroperable type or type parameters, the result of C_LOC provides an opaque “handle” for it. In an actual implementation, this handle might be the C address of the argument; however, only a C function that treats it as a void (generic) C pointer that cannot be dereferenced (6.5.3.2 in ISO/IEC 9899:2011) is likely to be portable.”
>
> (see http://isotc.iso.org/livelink/livelink?func=ll&objId=18770270&objAction=Open)
>
>
>> 2) pass this handle to
>> C/python,
>
> which is likely to be non-portable if the C function treats it as anything other than a void C pointer.

In my use case, C/python treats it as a void pointer, so no issues there.

>
>> 3) pass this handle back from C/python and then to fortran,
>> convert it back to a fortran derived type pointer using c_f_pointer,
>> and deallocate the memory. I've tested this in gfortran and it
>> appears to work (the fortran memory is deallocated). I'm wondering is
>> this guaranteed by the standard, or am I just lucky?
>
> This sounds like an application where disciplined testing would be critical.  I’d want to
> have a test to ensure the desired behavior with future changes to the derived type or changes
> to the compiler or changes to a different compilers if desired.  At a minimum, I think it
> would be important to include comments if the code is non-portable.

This appears to be the tricky one.  One might argue that the mere
existence of C_LOC and C_F_POINTER would imply that a round trip is
supported.  However, I know for a fact that deallocation on the return
trip to fortran does not work with all compilers that claim to support
the Fortran 2015 standard (although it does work for all but one that
I know of).

-Jeff



More information about the Fortran mailing list