Calling a C function from Fortran where the C function name was originally passed in from C

☆樱花仙子☆ 提交于 2019-12-02 02:41:02

When passing scalar values between Fortran and C, you have basically two options:

  • You pass them by reference: On the C-side you have to make sure, that you use pointers to those scalars.

  • You pass them by value: On the Fortran side you have to make sure that you use the VALUE attribute, as already suggested by other posts.

As for the intent(in) attribute, it can stay there, as it does not affect, whether the variable is passed by value or reference. In Fortran, arguments are always passed by reference unless you specify the VALUE attribute. The attribute intent(in) only tells the compiler to prevent a usage of that dummy argument in the routine, which would change its value.

Additional note on the naming: You should specify your Fortran routine fortranRoutine also with bind(c). This way you can specify its name as seen from C, even if it is inside a module:

module my_interface
  use iso_c_binding

contains

  subroutine fortranRoutine(calledFromFortran) bind(c, name='fortranroutine')
  ...
  end subroutine fortranRoutine

end module my_interface

This way you can be sure, the name of the function to be called from C is fortranroutine, independent of the convention of the compiler to append underscores, prepend module names or convert names to lower case. Consequently, you would have a a header file in C, which should work compiler independently:

extern "C" {
  void fortranroutine(void(int status));
};

I would change the interface definition to read

interface
    subroutine calledfromFortran(status) bind (c)
        use iso_c_binding
        integer(kind = c_int), VALUE :: status
    end subroutine calledfromFortran
end interface

I am not sure what intent(in) was, but that bit of the code does not look right. Apart for that, the rest looks (at first pass) reasonable and right.

Note. The ISO C bindings were only added in the 2003 releae of the FORTRAN language, so if you are using an older version it might be worth checking the compiler documentation for details. Some compilers allow ISO C bindings, but maybe called slightly differently than that I have displayed above.


Edit. Having looked into the intent keyword, you might try using intent(in) in conjunction with the following type declaration, that follows the interface definition

integer (c_int), parameter :: one = 2

I hope this helps.

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