Quantcast
Viewing all articles
Browse latest Browse all 10

Just a follow up in case

Just a follow up in case anybody else is interested. I still haven't figured out how to create a fortran function that returns a C_PTR to fortran allocated memory but I was able to do it via a fortran subroutine as follows:

!Given the address of a C_PTR this subroutine allocates the memory required
!for a SomeDerivedType derived data type, initializes it with the given values,
!and stores the C_LOCated address in the C_PTR.
subroutine makeDerivedType_(cdt) bind (c, name='makeDerivedType_')
   use iso_c_binding
   type (C_PTR) :: cdt
   type (SomeDerivedType), pointer :: fdt
   allocate(fdt)    
   fdt%someInteger=4
   cdt = C_LOC(fdt)
end subroutine 

A corresponding fortran access routine would be something like:

!This subroutine converts the given C_PTR value to a fortran pointer making
!it accessible again from Fortran
subroutine examineDerivedType_(this) bind (c, name='examineDerivedType_')
   use iso_c_binding
   type (C_PTR), value :: this
   type (SomeDerivedType), pointer :: that
   call C_F_POINTER(this, that)
   write (*,*) "that%someInteger", that%someInteger
end subroutine

And finally, an example of using it from C:

extern void makeDerivedType_(void* m);
extern void examineDerivedType_(void* m);
int main( int argc, const char* argv[] )
{
      void* m = 0;
      makeDerivedType_(&m);
      examineDerivedType_(m);
}

Viewing all articles
Browse latest Browse all 10

Trending Articles