module mem_for_mpi_module
  use mpi
  use, intrinsic :: iso_c_binding

  implicit none

  private

  interface
    subroutine alloc_mpi_mem(asize, baseptr, ierr) bind(c, name='alloc_mpi_mem')
      use, intrinsic :: iso_c_binding
      integer(kind=c_int64_t), value :: asize
      type(c_ptr) :: baseptr
      integer(kind=c_int) :: ierr
    end subroutine alloc_mpi_mem

    function free_mpi_mem(baseptr) bind(c, name='free_mpi_mem')
      use, intrinsic :: iso_c_binding
      type(c_ptr), value :: baseptr
      integer(kind=c_int) :: free_mpi_mem
    end function free_mpi_mem
  end interface

  public :: alloc_mpif_mem, free_mpif_mem


contains


  subroutine alloc_mpif_mem(asize, baseptr, ierr)
    integer(kind=MPI_ADDRESS_KIND), intent(in) :: asize
    type(c_ptr), intent(out) :: baseptr
    integer, optional, intent(out) :: ierr

    integer(kind=c_int) :: cerr

    call alloc_mpi_mem( asize   = int(asize, kind=c_int64_t), &
      &                 baseptr = baseptr,                    &
      &                 ierr    = cerr                        )

    if (present(ierr)) ierr = int(cerr)

  end subroutine alloc_mpif_mem


  subroutine free_mpif_mem(baseptr, ierr)
    type(c_ptr)       :: baseptr
    integer, optional :: ierr

    integer(kind=c_int) :: cerr

    cerr = free_mpi_mem(baseptr)
    if (present(ierr)) ierr = int(cerr)
  end subroutine free_mpif_mem

end module mem_for_mpi_module
