Fortran Coder

查看: 2470|回复: 0
打印 上一主题 下一主题

[原创] Fortran 调用C语言qsort

[复制链接]

159

帖子

2

主题

1

精华

大师

Vim

F 币
961 元
贡献
469 点

规矩勋章

跳转到指定楼层
楼主
发表于 2022-1-13 11:56:04 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 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)







分享到:  微信微信
收藏收藏 点赞点赞 点踩点踩
您需要登录后才可以回帖 登录 | 极速注册

本版积分规则

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

GMT+8, 2024-4-26 20:56

Powered by Tencent X3.4

© 2013-2024 Tencent

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