Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Fortran callback to C

153 views
Skip to first unread message

John McFarland

unread,
Mar 19, 2009, 8:54:51 PM3/19/09
to
I'm trying to pass a function pointer from C to Fortran and have
Fortran call back to that function. My Fortran code looks like this:
--------------Fortran----------------------
! Callback to a C function with no return value and no arguments
SUBROUTINE call_sub(fc) BIND(c)
USE ISO_C_BINDING
TYPE (C_FUNPTR) :: fc

PROCEDURE(), POINTER :: f

CALL C_F_PROCPOINTER(fc, f)

CALL f()
END SUBROUTINE call_sub
-------------------------------------------

And the C code to to test this looks like this:
-------------------C-----------------------------
#include <stdio.h>

void hello(void) {
printf("Hello\n");

}

// Declaration of Fortran function that will make the callback
void call_sub(void(*f)(void));

int main(void) {
call_sub(hello);
}

-----------------------------------------------

I'm using g95 and gcc, but I'm getting a segfault at CALL f(). Am I
doing something wrong in the Fortran code?

Thanks.

Jugoslav Dujic

unread,
Mar 20, 2009, 5:18:25 AM3/20/09
to

It's already beginning to be a common mistake... sort of ISO_C_BINDING
FAQ. It isn't obvious though, I must admit:

SUBROUTINE call_sub(fc) BIND(c)
USE ISO_C_BINDING
TYPE (C_FUNPTR) :: fc

C_PTR (and C_FUNPTR) is an address already. However, Fortran still
has the default of calling (as if) by reference, so the above piece of
code expects a _reference_ to _an address_, which matches a C void**
rather than void*.

Instead, you need:

TYPE (C_FUNPTR), VALUE :: fc

to reduce indirection level by one.

--
Jugoslav
www.xeffort.com
Please reply to the newsgroup.
You can find my real e-mail on my home page above.

John McFarland

unread,
Mar 20, 2009, 9:52:54 AM3/20/09
to

Thanks a lot, that did it.

0 new messages