Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a Fortran integer value to a malloc-allocated C memory target

Suppose you had created a Fortran array(:) of pointers to memory allocated in C by malloc (as shown in best answer, code repeated below). Is there a way to write an integer value into this allocated memory by using the Fortran array, i.e. the iso_c_bindings? Or would I have to do this in C?

#include "stdlib.h"
int *create_storage()
{
   /* Array of four integers. */
   return malloc(sizeof(int) * 4);
}

void destroy_storage(int *ptr)
{
   free(ptr);
}


PROGRAM fortran_side
  USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_PTR, C_F_POINTER, C_INT
  IMPLICIT NONE
  INTERFACE
    FUNCTION create_storage() BIND(C, NAME='create_storage')
      USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_PTR
      IMPLICIT NONE
      TYPE(C_PTR) :: create_storage
    END FUNCTION create_storage
    SUBROUTINE destroy_storage(p) BIND(C, NAME='destroy_storage')
      USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_PTR
      IMPLICIT NONE
      TYPE(C_PTR), INTENT(IN), VALUE :: p
    END SUBROUTINE destroy_storage
  END INTERFACE
  TYPE(C_PTR) :: p
  INTEGER(C_INT), POINTER :: array(:)
  !****
  p = create_storage()
  CALL C_F_POINTER(p, array, [4])   ! 4 is the array size.
  ! Work with array...
  CALL destroy_storage(p)
END PROGRAM fortran_side
like image 259
BastH Avatar asked Jun 11 '20 16:06

BastH


1 Answers

You are almost there. Just use array

array(4) = 20

If the code is compiled with -g and then stepped through with the debugger, when destroy_storage is reached, printing p[3] will show the value of 20.

like image 71
cup Avatar answered Nov 04 '22 12:11

cup