Pointers 一个指针用于不同类型的Fortran
我正在尝试编写一个过程,它存储用户数组的地址以供进一步处理。此测试程序中包含问题:Pointers 一个指针用于不同类型的Fortran,pointers,fortran,Pointers,Fortran,我正在尝试编写一个过程,它存储用户数组的地址以供进一步处理。此测试程序中包含问题: program test_ptr real(4), target, allocatable :: i4(:,:) real(8), target, allocatable :: i8(:,:) real(4), pointer :: p(:,:) allocate(i4(2,2)) allocate(i8(2,2)) p => i4 ! ok p
program test_ptr
real(4), target, allocatable :: i4(:,:)
real(8), target, allocatable :: i8(:,:)
real(4), pointer :: p(:,:)
allocate(i4(2,2))
allocate(i8(2,2))
p => i4 ! ok
p => i8 ! compile error
end
编译器建议为不同类型创建不同的指针。
但我不想为real(4)和real(8)创建单独的指针。我正试图使通用和紧凑的解决方案,并有一个指针为不同类型的数据。有可能吗?可以使用
p
的(无限)多态性来实现这一点
program test_ptr
implicit none
real(kind(0.)), target :: r4(2,2)
real(kind(0d0)), target :: r8(2,2)
class(*), pointer :: p(:,:)
! some assignments, etc.
if (...some crazy condition...) then
p => r4
else
p => r8
end if
select type (p)
type is (real(kind(0.)))
print *, p
type is (real(kind(0d0)))
print *, p
end select
end program
请特别注意
选择类型
,以便以后使用p
时,可以使用p
的(无限)多态性来执行此操作
program test_ptr
implicit none
real(kind(0.)), target :: r4(2,2)
real(kind(0d0)), target :: r8(2,2)
class(*), pointer :: p(:,:)
! some assignments, etc.
if (...some crazy condition...) then
p => r4
else
p => r8
end if
select type (p)
type is (real(kind(0.)))
print *, p
type is (real(kind(0d0)))
print *, p
end select
end program
请特别注意
选择类型
,以便以后使用p
时使用。如果您确实想存储地址,我会小心使用多态性。指向多态变量的指针通常指向与实际数据地址不同的描述符。考虑使用<代码>类型(CY-PTR)定义在<代码> ISOLL CXIONION/COD>模块和函数<代码> CyLoCo()/<代码>中获取地址。它不必只用于与C的接口,在纯Fortran中有几个地方它很方便。如果你真的想存储地址,我会小心使用多态性。指向多态变量的指针通常指向与实际数据地址不同的描述符。考虑使用<代码>类型(CY-PTR)定义在<代码> ISOLL CXIONION/COD>模块和函数<代码> CyLoCo()/<代码>中获取地址。它不必只用于与C的接口,在纯Fortran中有几个地方它很方便。如果地址(在问题中)比指针更重要,请参阅Vladimir F的说明。谢谢,这是一个好主意,但我的编译器说:“(1)的无限多态性)尚不支持“.@vovo”,听起来像是gfortran错误消息。4.8.2(可能更早,但我没有检查何时)确实支持此构造。如果地址(在问题中)比指针更重要,请参阅Vladimir F的说明。谢谢,这是一个好主意,但我的编译器说:“(1)处的无限多态性尚不受支持”。@vovovo听起来像是gfortran错误消息。4.8.2(可能更早,但我没有检查何时)确实支持此构造。谢谢,但我无法理解它是如何工作的。如果p=c\u ptr(r4)
,那么我如何获取它下面的数据(如c中的*p
)?然后使用c\u指针()
子例程设置Fortran指针来指向数据。您必须知道该类型,因为它没有存储在c\u ptr
中。谢谢,但我无法理解它是如何工作的。如果p=c\u ptr(r4)
,那么我如何获取它下面的数据(如c中的*p
)?然后使用c\u指针()
子例程设置Fortran指针来指向数据。您必须知道类型,因为它不存储在c\u ptr
中。
program test_ptr
implicit none
real(kind(0.)), target :: r4(2,2)
real(kind(0d0)), target :: r8(2,2)
class(*), pointer :: p(:,:)
! some assignments, etc.
if (...some crazy condition...) then
p => r4
else
p => r8
end if
select type (p)
type is (real(kind(0.)))
print *, p
type is (real(kind(0d0)))
print *, p
end select
end program