2022-11-18

How can I protect a module variable that should only be readable through a pointer in fortran?

I have an example program that looks like this:

module important_module

integer, dimension(5), protected, target :: important_array
contains
function testFunction() result(important_array_pointer)
  integer, dimension(:), pointer    :: important_array_pointer

  integer        :: i

  do i = 1, size(important_array)
    important_array(i) = 0
  end do
  important_array_pointer=>important_array
  
end function testFunction

end module important_module

Program TEST

    use important_module
    integer, dimension(:), pointer    :: important_array_pointer

    important_array_pointer=>testFunction() 
    print *, important_array_pointer(1) ! prints 0
    important_array_pointer(1) = 1
    print *, important_array_pointer(1) ! prints 1

End Program TEST

I would like important_array to only be writable from within the important_module module, hence the protected definition. This is because this array is used in conjunction with the fortran FFTW interface and holds information where a fourier transform is performed on, and it's suboptimal to have the input- or output arrays of these operations be public or be accessible from anywhere outside of this module. This example simplifies this as a 1d integer array.

If I generate a pointer to this array, it still becomes writable from the outside, even though I expected some kind of violation error.

Is there a way to ensure that this variable is actually protected and cannot be written to from anywhere outside of the corresponding module?



No comments:

Post a Comment