首页 文章

Cpython和fortran链表之间的互操作性

提问于
浏览
2

我有一个类似的fortran链表

type :: node
    type(node), pointer :: next => null()
    integer :: value
end type node

理想情况下,我希望使用Cpython与此进行交互 . 我使用f2py程序创建了共享对象,使用了很多python的子程序 . 但是,f2py不能与派生类型一起使用 .

我的问题是,是否有可能使用cpython访问Fortran中的链接列表 . 我认为我需要遵循fortran来c到cpython路线 . 但是,我已经读过,因为fortran派生类型可以与c _2875146进行互操作 . 同样,帖子c-fortran interoperability - derived types with pointers似乎证实了这一点 .

我想知道是否有人知道是否绝对无法从cpython访问fortran中的链表 . 如果有可能,即使是间接或以一种全面的方式,我将不胜感激 .

谢谢你,马克

1 回答

  • 1

    正如BálintAradi在评论中已经提到的那样,节点不能与C的当前形式互操作 . 为此你需要将fortran指针改为C指针,但这使得在fortran中使用它非常痛苦 . 我能想到的最优雅的解决方案是将C互操作类型置于fortran类型中并保存C和fortran指针的单独版本 .

    实现如下所示,我还定义了在fortran中使用的便捷函数来分配,释放和初始化节点 .

    module node_mod
    
        use, intrinsic :: iso_c_binding
        implicit none
    
        ! the C interoperable type
        type, bind(c) :: cnode
            type(c_ptr) :: self = c_null_ptr
            type(c_ptr) :: next = c_null_ptr
            integer(c_int) :: value
        end type cnode
    
        ! the type used for work in fortran
        type :: fnode
            type(cnode) :: c
            type(fnode), pointer :: next => null()
        end type fnode
    
    contains
    
    recursive function allocate_nodes(n, v) result(node)
    
        integer, intent(in) :: n
        integer, optional, intent(in) :: v
        type(fnode), pointer :: node
        integer :: val
    
        allocate(node)
        if (present(v)) then
            val = v
        else
            val = 1
        end if
        node%c%value = val
        if (n > 1) then
            node%next => allocate_nodes(n-1, val+1)
        end if
    
    end function allocate_nodes
    
    recursive subroutine deallocate_nodes(node)
    
        type(fnode), pointer, intent(inout) :: node
        if (associated(node%next)) then
            call deallocate_nodes(node%next)
        end if
        deallocate(node)
    
    end subroutine deallocate_nodes
    
    end module node_mod
    

    正如您所看到的,访问“value”元素需要额外的“%c”,这有点令人讨厌 . 要使用python中先前定义的例程来检索链表,必须定义C互操作包装器并且必须链接C指针 .

    module node_mod_cinter
    
        use, intrinsic :: iso_c_binding
        use, non_intrinsic :: node_mod
    
        implicit none
    
    contains
    
    recursive subroutine set_cptr(node)
    
        type(fnode), pointer, intent(in) :: node
    
        node%c%self = c_loc(node)
        if (associated(node%next)) then
            node%c%next = c_loc(node%next%c)
            call set_cptr(node%next)
        end if
    
    end subroutine set_cptr
    
    function allocate_nodes_citer(n) bind(c, name="allocate_nodes") result(cptr)
    
        integer(c_int), value, intent(in) :: n
        type(c_ptr) :: cptr
        type(fnode), pointer :: node
    
        node => allocate_nodes(n)
        call set_cptr(node)
        cptr = c_loc(node%c)
    
    end function allocate_nodes_citer
    
    subroutine deallocate_nodes_citer(cptr) bind(c, name="deallocate_nodes")
    
        type(c_ptr), value, intent(in) :: cptr
        type(cnode), pointer :: subnode
        type(fnode), pointer :: node
    
        call c_f_pointer(cptr, subnode)
        call c_f_pointer(subnode%self, node)
        call deallocate_nodes(node)
    
    end subroutine deallocate_nodes_citer
    
    end module node_mod_cinter
    

    “* _nodes_citer”例程简单地处理不同的指针类型,而set_cptr子例程根据fortran指针链接C可互操作类型内的C指针 . 我添加了节点%c%self元素,以便可以恢复fortran指针并用于正确的释放,但是如果你不太关心它,那么它不是严格需要的 .

    此代码需要编译为共享库以供其他程序使用 . 我在我的linux机箱上使用了以下命令和gfortran .

    gfortran -fPIC -shared -o libnode.so node.f90
    

    最后,python代码分配10个节点的列表,打印出每个节点的节点%c%值,然后再次释放所有内容 . 另外,还示出了fortran和C节点的存储器位置 .

    #!/usr/bin/env python
    import ctypes
    from ctypes import POINTER, c_int, c_void_p
    class Node(ctypes.Structure):
        pass
    Node._fields_ = (
            ("self", c_void_p),
            ("next", POINTER(Node)),
            ("value", c_int),
            )
    
    def define_function(res, args, paramflags, name, lib):
    
        prot = ctypes.CFUNCTYPE(res, *args)
        return prot((name, lib), paramflags)
    
    def main():
    
        import os.path
    
        libpath = os.path.abspath("libnode.so")
        lib = ctypes.cdll.LoadLibrary(libpath)
    
        allocate_nodes = define_function(
                res=POINTER(Node),
                args=(
                    c_int,
                    ),
                paramflags=(
                    (1, "n"),
                    ),
                name="allocate_nodes",
                lib=lib,
                )
    
        deallocate_nodes = define_function(
                res=None,
                args=(
                    POINTER(Node),
                    ),
                paramflags=(
                    (1, "cptr"),
                    ),
                name="deallocate_nodes",
                lib=lib,
                )
    
        node_ptr = allocate_nodes(10)
    
        n = node_ptr[0]
        print "value", "f_ptr", "c_ptr"
        while True:
            print n.value, n.self, ctypes.addressof(n)
            if n.next:
                n = n.next[0]
            else:
                break
    
        deallocate_nodes(node_ptr)
    
    if __name__ == "__main__":
        main()
    

    执行此操作会给我以下输出:

    value f_ptr c_ptr
    1 15356144 15356144
    2 15220144 15220144
    3 15320384 15320384
    4 14700384 14700384
    5 15661152 15661152
    6 15661200 15661200
    7 15661248 15661248
    8 14886672 14886672
    9 14886720 14886720
    10 14886768 14886768
    

    有趣的是,两个节点类型都从相同的内存位置开始,因此并不真正需要节点%c%self,但这只是因为我对类型定义非常谨慎,这真的不应该被依赖 .

    你有它 . 即使不必处理链表也很麻烦,但是ctypes比f2py强大得多 . 希望从中得到一些好处 .

相关问题