My Project
programmer's documentation
Creating user arrays (cs_user_modules.f90)

Introduction

User subroutine for the definition of a user module. The following example illustrates the creation of user arrays called rwork and iwork.

Arrays declaration

The first step is to declare these two arrays at the very beginning of the module. The first one iwork is an allocatable array of one dimension whereas rwork is a pointer to a bidimensionnal array.

! Example: allocatable user arrays
integer, dimension(:), allocatable :: iwork
double precision, dimension(:,:), pointer :: rwork => null()

Arrays allocation

The init_user_module subroutine allocates rwork and iwork if they are not already allocated or associated (for rwork).

! Allocate arrays
subroutine init_user_module(ncel, ncelet)
! Arguments
integer, intent(in) :: ncel, ncelet
! Local variables
integer :: err = 0
if (.not.allocated(iwork)) then
allocate(iwork(ncelet), stat=err)
endif
if (err .eq. 0 .and. .not.associated(rwork)) then
allocate(rwork(3, ncelet), stat=err)
endif
if (err /= 0) then
write (*, *) "Error allocating array."
call csexit(err)
endif
return
end subroutine init_user_module

Access to arrays in C

It is possible to access the rwork array in the C part of the code. This can be done by using the get_user_module_rwork subroutine.

! Pass pointer to rwork array to C
function get_user_module_rwork() result(r) &
bind(c, name='get_user_module_rwork')
use, intrinsic :: iso_c_binding
implicit none
type(c_ptr) :: r
if (associated(rwork)) then
r = c_loc(rwork(1,1))
else
r = c_null_ptr
endif
end function get_user_module_rwork

Arrays freeing

Eventually, the finalize_user_module subroutine is used to free iwork and rwork.

! Free related arrays
subroutine finalize_user_module
if (allocated(iwork)) then
deallocate(iwork)
endif
if (associated(rwork)) then
deallocate(rwork)
endif
end subroutine finalize_user_module