c_loc -> c_ptr -> c_f_pointer round trip
Damian Rouson
damian@sourceryinstitute.org
Fri Apr 28 17:25:00 GMT 2017
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.
> 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.
I don’t know if it’s related, but the Introduction to the Fortran 2015 draft also includes
the following: “The argument to C_LOC can be a noninteroperable array.” I suppose there
must have been a previous restriction that disallowed noininteroperable arrays so if
your noninteroperable argument is an array, then using as an argument to C_LOC would not
have been standard-conforming prior to Fortran 2015.
Damian
who would love it if we moved to a communication medium with richer formatting so long URLs can be embedded as hyperlinks rather than disrupting the text, code snippets can have syntax-aware coloring, people can be tagged, some responses require only a button click or two, etc. (GitHub, anyone?)
More information about the Fortran
mailing list