我试图用ctypes从Python调用Fortran函数。我试图从一个子程序和一个函数(两个函数都具有相同的功能)中获得结果,但是我无法从函数中获得预期的输出,而子程序工作得很好。 问题是我有很多库使用Fortran函数而不是子程序。 Fortran函数和ctypes有什么问题吗?在
Fortran代码:
MODULE Vector
! Public types
TYPE VectorType
PRIVATE
DOUBLE PRECISION, DIMENSION(3):: components = 0.0d0
END TYPE VectorType
!---------------------------------------------------------------------
CONTAINS
!---------------------------------------------------------------------
SUBROUTINE newVect(this,vectorIn)
TYPE (VectorType), INTENT(OUT):: this
DOUBLE PRECISION, DIMENSION(3), INTENT(IN)::vectorIn
this%components = (/vectorIn(1), vectorIn(2), vectorIn(3)/)
END SUBROUTINE newVect
!---------------------------------------------------------------------
SUBROUTINE subVect(this,vectorOut)
TYPE(VectorType), INTENT (OUT):: vectorOut
TYPE(VectorType), INTENT (IN) :: this
vectorOut%components = this%components
END SUBROUTINE subVect
!----------------------------------------------------------------------
TYPE(VectorType) FUNCTION getVect(this) RESULT(vectorOut)
TYPE(VectorType), INTENT (IN) :: this
vectorOut%components = this%components
END FUNCTION getVect
!--------------------------------------------------------------------
END MODULE Vector
我使用的Python代码是:
^{pr2}$对于函数,我做了很多尝试,但始终没有得到正确的结果。要运行该程序,请尝试使用:
import pyctp.vector
newVect = pyctp.vector.vector((1.0,2.0,3.0))
newVect.subVect()
newVect.getVect()
子例程调用返回预期的向量,而函数调用返回空向量或充满垃圾的向量。在
首先,您应该将bind(C)属性添加到希望从Python中可见的所有过程和类型。 所有的Fortran类型都应该从iso\u绑定中获取,例如使用},您将确保它是可与c互操作的类型
real(c_double)
而不是{然后在python中传递所有参数作为引用:
^{pr2}$getVect的结果已经是VectorType,因此您可以直接访问它的组件。在
相关问题 更多 >
编程相关推荐