[Fortran] 纯文本查看 复制代码
module sorting_example_mod
use iso_c_binding
implicit none
interface
subroutine qsort_C(array, elem_count, elem_size, comparison_fun) bind(C,name="qsort")
use iso_c_binding, only: c_ptr, c_funptr,c_int
implicit none
type(*),intent(inout) :: array(*)
integer(c_int), value :: elem_count
integer(c_int), value :: elem_size
type(c_funptr), value :: comparison_fun
end subroutine qsort_C
end interface
contains
! user defined compare function
integer(c_int) function compare_real8(t1, t2) bind(C)result(flag)
real(kind=c_double), intent(in) :: t1, t2
if(t1 < t2) flag = -1_c_int
if(abs(t1-t2)<epsilon(1.d0)) flag = 0_c_int
if(t1 > t2) flag = 1_c_int
end function compare_real8
integer(c_int) function compare_int(t1, t2) bind(C)result(flag)
integer(c_int),intent(in) :: t1, t2
if(t1 < t2) flag = -1_c_int
if(t1 == t2) flag = 0_c_int
if(t1 > t2) flag = 1_c_int
end function compare_int
end module sorting_example_mod
program test_qsort
use iso_c_binding
use sorting_example_mod
real(kind=8)::a(5)
integer::b(5)=[1,3,4,2,5]
call random_number(a)
call qsort_C(a,5,kind(a),c_funloc(compare_real8))
write(*,*)a
call qsort_C(b,5,kind(b),c_funloc(compare_int))
write(*,*)b
end program test_qsort