Using assumed-rank Fortran array as derived type component

时间:2017-06-15 10:15:18

标签: arrays fortran polymorphism

I'm looking for some general advice as to the best approach to creating a derived type that stores arbitrary data with arbitrary rank.

Say I have a derived type Result with a data component (amongst others):

type, public :: Result
    private
    class(*), allocatable :: data
    ...
end type

which is initialised by some procedure (called from an interface Result):

function init(data) result(this)
  type(Result) :: this
  class(*), intent(in) :: data

  allocate(this%data, source=data)
end function

This works fine for scalar data, but I'm unsure about how to go about setting it up for arbitrary-rank data. I know procedures can accept assumed-rank parameters, so data in the init(data) function could be data(..), but I'm not sure it's possible to specify the derived type property this%data as being a assumed rank?

The other way I thought of doing it would be to store the arbitrary rank data as a scalar, if such a thing is possible in Fortran? This would be equivalent to using the serialize() and unserialize() functions in PHP. If anyone has any guidance on a similar approach, I'd be very grateful.

Ultimately I'd like to be able to do something like this:

type(Result) :: scalarResult
type(Result) :: 2DResult

scalarResult = Result(data=1.234)
2DResult = Result(data=[[1,2,3],[4,5,6]])

1 个答案:

答案 0 :(得分:1)

不可能有假定的等级派生类型组件。您需要找到另一种解决方案,例如Vladimir建议的解决方案。另一种想法是存储数据的C_LOC和等级,调用构造适当C描述符的C例程,然后使用假定等级参数回调到Fortran例程。

请记住,你不能在Fortran中做出很多假设等级 - SELECT RANK在2015年之前不存在。

相关问题