iso_c_binding calling C routine with pointers from Fortran with arrays

╄→尐↘猪︶ㄣ 提交于 2019-12-04 16:31:53

Do not over-complicate it. Don't pass the pointers, but pass the arrays by reference

Also, a function must be used in an expression, not in a call statement.

module raytracing
  Interface
    integer (C_INT) function photon_trace(x_init, x_final) & 
      bind(C, name='photon_trace')  
      use , intrinsic :: ISO_C_BINDING
      implicit none
      real(c_double) :: x_init(4), x_final(4)
    end function photon_trace
  end interface
end module raytracing  

program main_dummy
! compile: f95 raytracing.f90 main_dummy.f90 dummy_trace.o -o main
use, intrinsic :: ISO_C_BINDING
use raytracing

implicit none

real(c_double), dimension(0:3) :: x_in, x_fin
integer ie

x_in = (/1,2,3,4/)
x_fin = (/0,0,0,0/)


write(*,*)'x_in, x_fin before = ', x_in, x_fin
ie = photon_trace(x_in,x_fin)
write(*,*)'x_in, x_fin after = ', x_in, x_fin


end program main_dummy

In C interoperable procedures Fortran passes pointers to the variables, unless you use value. This is called pass by reference.

> gfortran ray.c ray.f90
> ./a.out 
 x_in, x_fin before =    1.0000000000000000        2.0000000000000000        3.0000000000000000        4.0000000000000000        0.0000000000000000        0.0000000000000000        0.0000000000000000        0.0000000000000000     
 x_in, x_fin after =    1.0000000000000000        2.0000000000000000        3.0000000000000000        4.0000000000000000        2.0000000000000000        3.0000000000000000        4.0000000000000000        5.0000000000000000

P.S. gcc 4.4 very old, but it theoretically it knows the C interop stuff. Try it and you will see.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!