如何将 Cray 指针传递给子程序?

How to pass a Cray pointer into subroutine?

我将一个用变量映射的 Cray 指针传递给 Fortran 子例程。说明如下:

program test
  integer val
  pointer (ptr_val, val)

  print *, "1:", loc(val)
  print *, "1:", ptr_val

  CALL DPMALLOC(ptr_val, sizeof(val))

  print *, "2:", loc(val)
  print *, "2:", ptr_val

  val = 999
  call foo(val)

end program test

subroutine foo(val)
  integer val
  print *, "3:",val
  print *, "3:", loc(val)
  print *, "3:", ptr_val
  call DPMALLOC(ptr_val, sizeof(val))
  print *, "4:", ptr_val
  print *, "4:", loc(val)
  return
end subroutine foo
void dpmalloc_(void **data, int *size){ 
    *data =(void *) malloc(*size);
    printf("malloc\n");
}

输出:

 1:                   0
 1                    0
 2:             30743328
 2:             30743328
 3:         999
 3:             30743328
 3:  7.82827652E-38
 4:  7.82833033E-38
 4:             30743328

因此,我似乎不能在子程序中使用全局指针。我该如何解决?

正如 francescalus 指出的那样,您确实应该始终使用 IMPLICIT NONE。这非常非常重要。如果您一定不必关心严格的 FORTRAN77 兼容性,因为 Cray 指针无论如何都是一种扩展。所以请使用 IMPLICIT NONE!

这会告诉你 ptr_val 在子例程中未定义。

相反,您应该传递指针,而不是数组,并在子例程中再次声明指针关联:

program test
  implicit none

  integer val
  pointer (ptr_val, val)

  print *, "1:", loc(val)
  print *, "1:", ptr_val

  CALL DPMALLOC(ptr_val, sizeof(val))



  print *, "2:", loc(val)
  print *, "2:", ptr_val

  val = 999
  call foo(ptr_val)

end program test

subroutine foo(ptr_val)
  implicit none

  integer val
  pointer (ptr_val, val)

  print *, "3:",val
  print *, "3:", loc(val)
  print *, "3:", ptr_val
  call DPMALLOC(ptr_val, sizeof(val))
  print *, "4:", ptr_val
  print *, "4:", loc(val)
  return
end subroutine foo

输出:

> ./a.out 
 1:                    0
 1:                    0
malloc
 2:             10391632
 2:             10391632
 3:         999
 3:             10391632
 3:             10391632
malloc
 4:             10391392
 4:             10391392