How to allocate an array inside fortran routine “called” from C

前端 未结 3 620
刺人心
刺人心 2020-12-21 04:09

I think title says what I need. I know we can use \"asd\" function to do this, but for some reasons I need to do the allocation in Fortran (i.e. in subroutine \"asd_\"). Her

3条回答
  •  青春惊慌失措
    2020-12-21 05:05

    Here is also another solution, if you want to use Fortran intrinsic types. This was my case, since I needed to call routines from an external library, using the pre-specified data types. This is basically done with a wrapper Fortran subroutine. Here is the C code:

    void mywrap_(void **);
    void myprint_(void *);
    
    main () {
      void *d;
      mywrap_(&d);
      myprint_(d);
      return 0;
    }
    

    And here is the wrapper:

      subroutine mywrap(b)
      implicit none
      include "h.h"     
      type(st), target, save :: a
      integer, pointer :: b
      interface 
         subroutine alloc(a)
            include "h.h"
            type(st) a
         end subroutine alloc
      end interface
    
      call alloc(a)
      b => a%i
      end
    

    And the Fortran codes:

      subroutine alloc(a)
      implicit none 
      include "h.h"
      type(st) a
    
      a%i = 2
      a%r = 1.5
      if (allocated(a%s)) deallocate(a%s)
      allocate(a%s(2))
      a%s(1) = 1.23
      a%s(2) = 1234
      end
      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      subroutine myprint(a)
      implicit none
      include "h.h"     
      type(st) a
    
      print *,"INT: ", a%i
      print *,"REAL: ", a%r
      print *,"ALLOC: ", a%s
      end
    

    And the header file "h.h":

      type st
         sequence
         integer i
         real r
         real, allocatable :: s(:)
      end type
    

    Note, this way all the objects are opaque in the C.

提交回复
热议问题