本帖最后由 Transpose 于 2023-8-22 11:00 编辑
[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
1.这段程序调用了C语言的`qsort`函数,用法和C的qsort函数类似,自行书写`compare`子程序即可使用。
2. c中的第二第三个参数是`size_t`类型的,这里使用的是`int`
参考自
Correctly calling qsort from C - Fortran Discourse (fortran-lang.discourse.group)
|