|
| 1 | +! File : fortran_callback_runme.F90 |
| 2 | + |
| 3 | +#include "fassert.h" |
| 4 | + |
| 5 | +module fortran_callback_mod |
| 6 | + use, intrinsic :: ISO_C_BINDING |
| 7 | + use ISO_FORTRAN_ENV |
| 8 | + implicit none |
| 9 | + integer, parameter :: STDOUT = OUTPUT_UNIT |
| 10 | + integer(C_INT), save, public :: module_int |
| 11 | +contains |
| 12 | + |
| 13 | +function myexp(left, right) bind(C) & |
| 14 | + result(fresult) |
| 15 | + use, intrinsic :: ISO_C_BINDING |
| 16 | + integer(C_INT), intent(in), value :: left |
| 17 | + integer(C_INT), intent(in), value :: right |
| 18 | + integer(C_INT) :: fresult |
| 19 | + |
| 20 | + fresult = left ** right |
| 21 | +end function |
| 22 | + |
| 23 | +function mywrite() bind(C) & |
| 24 | + result(fresult) |
| 25 | + use, intrinsic :: ISO_C_BINDING |
| 26 | + integer(C_INT) :: fresult |
| 27 | + ! write(STDOUT,*) "Hi there" |
| 28 | + fresult = 256_c_int |
| 29 | +end function |
| 30 | + |
| 31 | +subroutine store_an_int(i) bind(C) |
| 32 | + use, intrinsic :: ISO_C_BINDING |
| 33 | + integer(C_INT), value, intent(in) :: i |
| 34 | + ! write(STDOUT,*) "Got an integer: ", i |
| 35 | + module_int = i |
| 36 | +end subroutine |
| 37 | + |
| 38 | +end module |
| 39 | + |
| 40 | +program fortran_callback_runme |
| 41 | + call test_callback |
| 42 | +contains |
| 43 | + |
| 44 | +subroutine test_callback |
| 45 | + use fortran_callback |
| 46 | + use fortran_callback_mod |
| 47 | + integer(C_INT) :: i |
| 48 | + procedure(call_binary_cb), pointer :: unused => NULL() |
| 49 | + procedure(binary_op), pointer :: bin_op_ptr => NULL() |
| 50 | + |
| 51 | + ! Use callbacks with Fortran module pointers |
| 52 | + bin_op_ptr => myexp |
| 53 | + i = call_binary(myexp, 2, 3) |
| 54 | + ASSERT(i == 8) |
| 55 | + i = call_things(mywrite) |
| 56 | + ASSERT(i == 256) |
| 57 | + call also_call_things(store_an_int, 999) |
| 58 | + ASSERT(module_int == 999) |
| 59 | + |
| 60 | + ! Get a C callback |
| 61 | + bin_op_ptr => get_a_callback("mul") |
| 62 | + ASSERT(associated(bin_op_ptr)) |
| 63 | + ASSERT(bin_op_ptr(2, 5) == 10) |
| 64 | + |
| 65 | + bin_op_ptr => get_a_callback("add") |
| 66 | + ASSERT(associated(bin_op_ptr)) |
| 67 | + ASSERT(bin_op_ptr(2, 5) == 7) |
| 68 | + |
| 69 | + bin_op_ptr => get_a_callback("nopenope") |
| 70 | + ASSERT(.not. associated(bin_op_ptr)) |
| 71 | + |
| 72 | +end subroutine |
| 73 | +end program |
| 74 | + |
| 75 | + |
0 commit comments