sockets programming gfortran

烂漫一生 提交于 2019-12-05 05:54:25

You can make use of the ISO_C_Binding introduced in Fortran 2003 to access C library functionality, this is the cleanest and most portable option you have. The Gfortran documentation has some details on it, as any other vendor manual. There are also some projects aiming to implement interfaces to POSIX for Fortran 90: fortranposix and posix90. But as I said a proper C-Binding interface using the F2003 capabilities is probably the cleanest option, see also the fortranwiki.

Edit: Here is your code with the ISO-C-Binding glue added (tested with gfortran 4.4.5):

program testsocket
  use, intrinsic ::  iso_c_binding

  implicit none

  interface
    function socket(domain, type, protocol) bind(c, name="socket")
      use, intrinsic :: iso_c_binding
      integer(kind=c_int) :: socket
      integer(kind=c_int), value :: domain, type, protocol
    end function socket
  end interface

  integer :: sock

  sock = socket(2_c_int, 1_c_int, 6_c_int)

  write(*,*) "Socket returned: ", sock

end program testsocket

Here's a guess. You're a graduate student in science or engineering (but not computer science or computer engineering) and your boss was born before 1950. If so, I have stood in your shoes (except that in my case the requirement was to use Fortran 77). I feel your pain.

As you probably know, Fortran does not use header files to prototype function calls in the same way C does. You can call a Fortran function without the header, when the types of the arguments are not checked.

However, there is this trouble -- or there used to be this trouble, for my most recent experience is several years out of date. Compared to C, GNU Fortran prepends a hidden underscore to the name of each function. It also lower-cases the function name.

The readelf -a program can help you here. Use it on the object file your Fortran compiler emits. Look in the output for the socket symbol. If my recollection is right, you'll see an _socket in there.

If you really, really cannot use any C at all -- even to make a wrapper function with the C name _socket() -- then I admit that I do not know what you should do next. In that case, you may be stuck in a tight spot. Either way, good luck.

Update: I recommend @M.S.B.'s comment below.

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