title: Fortran serialization using C_LOC and C_F_POINTER
body: <p>I'm looking for a Fortran Library or preferred method of serializing data to a memory buffer in Fortran. </p>
  
  <p>After researching the topic, I found examples using the EQUIVALENCE statement and the TRANSFER intrinsic function. I wrote code to test them and they both worked. In my limited testing, the transfer function seems to be quite a bit slower than the equivalence statement. However, I have found several references stating that in general not to use the equivalence statement. </p>
  
  <p>So, I've been trying to come up with another way to serialize data efficiently. After ready up on the Fortran 2003 spec I discovered that I could use the C_LOC and C_F_POINTER together to cast my "byte" array into the desired data type (int, real, etc..). Initial testing shows that it is working and is faster than the transfer function. An example program is listed below. I was wondering if this is valid use of the C_LOC and C_F_POINTER functions.</p>
  
  <p>Thanks!</p>
  
  <pre><code>  program main
      use iso_c_binding
      implicit none
  
  
      real(c_float)             :: a, b, c
      integer(c_int8_t), target :: buf(12)
  
      a = 12345.6789_c_float
      b = 4567.89123_c_float
      c = 9079.66788_c_float
  
      call pack_float( a, c_loc(buf(1)) )
      call pack_float( b, c_loc(buf(5)) )
      call pack_float( c, c_loc(buf(9)) )
  
      print '(A,12I5)', 'Bin: ', buf
  
  
    contains
  
  
      subroutine pack_float( src, dest )
        implicit none
        real(c_float), intent(in) :: src
        type(c_ptr), intent(in)   :: dest
        real(c_float), pointer    :: p
        call c_f_pointer(dest, p)
        p = src
      end subroutine
  
  
    end program
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>Bin:   -73  -26   64   70   33  -65 -114   69  -84  -34   13   70
  </code></pre>
  
  <p>I also coded this up in Python to double check the answer above. The code and output is listed below.</p>
  
  <pre><code>import struct
  
  a = struct.pack( '3f', 12345.6789, 4567.89123, 9079.66788)
  b = struct.unpack('12b', a)
  print b
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>(-73, -26, 64, 70, 33, -65, -114, 69, -84, -34, 13, 70)
  </code></pre>