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

时间:2016-10-11 07:06:09

标签: fortran fortran77 cray-pointers

我将一个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

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

1 个答案:

答案 0 :(得分:1)

正如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