'allocate'함수에 대한 래퍼를 쓰려고합니다. 즉, 배열과 차원을 받고, 메모리를 할당하고 할당 된 배열을 반환하는 함수를 작성하려고합니다. 가장 중요한 점은 함수가 다른 순위의 배열에서도 작동해야한다는 것입니다. 하지만 함수 인터페이스에서 배열의 순위를 명시 적으로 지정해야합니다.이 경우 코드는 특정 순위의 배열을 매개 변수로 전달하면 컴파일됩니다. 예를 들어,이 코드는 컴파일되지 않습니다 :'allocate'에 대한 래퍼 작성 방법
module memory_allocator
contains
subroutine memory(array, length)
implicit none
real(8), allocatable, intent(out), dimension(:) :: array
integer, intent(in) :: length
integer :: ierr
print *, "memory: before: ", allocated(array)
allocate(array(length), stat=ierr)
if (ierr /= 0) then
print *, "error allocating memory: ierr=", ierr
end if
print *, "memory: after: ", allocated(array)
end subroutine memory
subroutine freem(array)
implicit none
real(8), allocatable, dimension(:) :: array
print *, "freem: before: ", allocated(array)
deallocate(array)
print *, "freem: after: ", allocated(array)
end subroutine freem
end module memory_allocator
program alloc
use memory_allocator
implicit none
integer, parameter :: n = 3
real(8), allocatable, dimension(:,:,:) :: foo
integer :: i, j, k
print *, "main: before memory: ", allocated(foo)
call memory(foo, n*n*n)
print *, "main: after memory: ", allocated(foo)
do i = 1,n
do j = 1,n
do k = 1, n
foo(i, j, k) = real(i*j*k)
end do
end do
end do
print *, foo
print *, "main: before freem: ", allocated(foo)
call freem(foo)
print *, "main: after freem: ", allocated(foo)
end program alloc
컴파일 오류 :
gfortran -o alloc alloc.f90 -std=f2003
alloc.f90:46.14:
call memory(foo, n*n*n)
1
Error: Rank mismatch in argument 'array' at (1) (1 and 3)
alloc.f90:60.13:
call freem(foo)
1
Error: Rank mismatch in argument 'array' at (1) (1 and 3)
같은 래퍼 ..
감사를 구현하는 방법은 없나요!
고마워요! 할당 자 모듈에서 코드 중복이 필요하지만 최소한이 할당 자 함수를 호출 할 때는 공통 이름을 사용할 수 있습니다. 이것이 내가 원했던 것이다. – robusta