[J3] Question about C_F_Pointer
Vipul Parekh
parekhvs at gmail.com
Mon May 3 19:07:46 UTC 2021
On Sun, May 2, 2021 at 9:09 PM Van Snyder via J3 <j3 at mailman.j3-fortran.org>
wrote:
> ..
> Or maybe I've missed something and I'm unnecessarily doing things the hard
> way.
>
Yes, both.
You've missed out on the other unlimited polymorphic type
introduced starting Fortran 2018, TYPE(*). This type is what you can
consider if you are looking to "to pass Fortran objects through C code and
thence onward to Fortran code".
You may want to review the following trivial example:
C code:
#include <stdio.h>
// Prototype for Fortran callback function
typedef void (*pCallback)(void *);
void C_func(void *Fobj, pCallback Callback_Func) {
Callback_Func(Fobj);
}
Fortran:
module m
use, intrinsic :: iso_c_binding, only : c_loc, c_f_pointer
abstract interface
subroutine Icallback( Fo ) bind(C)
! Argument list
type(*), intent(in), target :: Fo
end subroutine
end interface
interface
subroutine C_func( Fo, cb ) bind(C, name="C_func")
import :: Icallback
! Argument list
type(*), intent(in) :: Fo
procedure(Icallback) :: cb
end subroutine
end interface
type :: t
character(len=:), allocatable :: s
end type
contains
subroutine My_Callback( Fo ) bind(C)
! Argument list
type(*), intent(in), target :: Fo
! Local objects
type(t), pointer :: bar
call c_f_pointer( c_loc(Fo), fptr=bar )
if ( allocated(bar%s) ) then
print *, "In My_Callback: ", bar%s
end if
bar => null()
end subroutine
end module
use m
type(t) :: foo
foo%s = "Hello World!"
call C_func( foo, My_Callback )
end
Two processors I tried, in conjunction with their companion C processors,
produce programs that give the following output:
In My_Callback: Hello World!
Vipul Parekh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.j3-fortran.org/pipermail/j3/attachments/20210503/e667c180/attachment.htm>
More information about the J3
mailing list