c_associated() 和 associated() 检查关联有什么区别?
Any difference between c_associated() and associated() for checking association?
在下面的代码中,我尝试检查 C 指针的关联状态(1)通过直接使用 c_associated()
指向 C 指针,或(2)使用 associated()
指向从 c_f_pointer()
.
获得的 Fortran 指针
module test_m
use iso_c_binding
implicit none
contains
subroutine sub( cp )
type(c_ptr) :: cp
integer, pointer :: fp
print *, "cp ? ", c_associated( cp ) !! Line 1
call c_f_pointer( cp, fp )
print *, "fp ? ", associated( fp ) !! Line 2
end subroutine
end module
program main
use test_m
implicit none
type(c_ptr) :: cp
integer, target :: x
! cp = c_loc( x ) !! => T T
cp = c_null_ptr !! => F F
call sub( cp )
end
在上述情况下,第 1 行和第 2 行的结果似乎总是相同。但是如果 cp
可能是空指针,我是否应该先使用 c_associated()
来检查状态的 cp
然后仅当 cp
保证关联(即不为空)时才使用 c_f_pointer()
?
c_f_pointer
将 (Fortran) 指针与 C 指针的目标相关联。指向 的 C 指针必须有 目标。
是的,如果有可能没有关联,你应该检查一下C指针的关联状态。
在下面的代码中,我尝试检查 C 指针的关联状态(1)通过直接使用 c_associated()
指向 C 指针,或(2)使用 associated()
指向从 c_f_pointer()
.
module test_m
use iso_c_binding
implicit none
contains
subroutine sub( cp )
type(c_ptr) :: cp
integer, pointer :: fp
print *, "cp ? ", c_associated( cp ) !! Line 1
call c_f_pointer( cp, fp )
print *, "fp ? ", associated( fp ) !! Line 2
end subroutine
end module
program main
use test_m
implicit none
type(c_ptr) :: cp
integer, target :: x
! cp = c_loc( x ) !! => T T
cp = c_null_ptr !! => F F
call sub( cp )
end
在上述情况下,第 1 行和第 2 行的结果似乎总是相同。但是如果 cp
可能是空指针,我是否应该先使用 c_associated()
来检查状态的 cp
然后仅当 cp
保证关联(即不为空)时才使用 c_f_pointer()
?
c_f_pointer
将 (Fortran) 指针与 C 指针的目标相关联。指向 的 C 指针必须有 目标。
是的,如果有可能没有关联,你应该检查一下C指针的关联状态。