Fortran Coder

查看: 1080|回复: 0

[原创] Fortran 调用C语言qsort

[复制链接]

114

帖子

2

主题

1

精华

大师

Vim

F 币
775 元
贡献
387 点

规矩勋章

发表于 2022-1-13 11:56:04 | 显示全部楼层 |阅读模式
本帖最后由 Transpose 于 2022-1-13 12:04 编辑

[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(c_ptr), value       :: 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(s1, s2) bind(C)result(flag)
        type(c_ptr), value :: s1, s2
        real(kind=8), pointer :: t1, t2
        call c_f_pointer(s1, t1)
        call c_f_pointer(s2, 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(s1, s2) bind(C)result(flag)
        type(c_ptr), value :: s1, s2
        integer, pointer :: t1, t2
        call c_f_pointer(s1, t1)
        call c_f_pointer(s2, 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),target::a(5)
    integer,target::b(5)=[1,3,4,2,5]
    call random_number(a)
    call qsort_C(c_loc(a(1)), &
        elem_count = 5, &
        elem_size  = 8, &
        comparison_fun = c_funloc(compare_real8))
    write(*,*)a
    call qsort_C(c_loc(b(1)), &
        elem_count = 5, &
        elem_size  = 4, &
        comparison_fun = 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)







您需要登录后才可以回帖 登录 | 极速注册

本版积分规则

捐赠本站|Archiver|关于我们 About Us|小黑屋|Fcode ( 京ICP备18005632-2号 )

GMT+8, 2023-6-7 04:18

Powered by Tencent X3.4

© 2013-2023 Tencent

快速回复 返回顶部 返回列表