- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Is there a way to call public static methods in a C++ class from Fortran? The way I have called C from Fortran is to use an interface block with BIND.
Link Copied
3 Replies
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
No there is no way to do this from Fortran. C++ has information hidden from the Fortran compiler.
------
Wendy
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Because the member function is static, you could always write an ordinary (non-member) function with extern "C" linkage to forward the call.
Similar forwarding functions, that also have a pointer-to-an-object-of-the-class parameter/C_PTR argument, can be written to call non-static member functions, with fortran just treating the C_PTR as an opaque handle to the class object.
[cpp]// The class with the public static member function.
class my_cpp_class
{
public:
static void do_some_static_stuff(float* f)
{
*f = 1234.56f;
}
};
// Forwarding function accessible from fortran.
extern "C" void static_stuff_forwarder(float *f)
{
my_cpp_class::do_some_static_stuff(f);
}
[/cpp] [fortran]PROGRAM CallCppStaticMethod
USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_FLOAT
IMPLICIT NONE
INTERFACE
SUBROUTINE do_some_static_stuff(f) &
BIND(C,NAME='static_stuff_forwarder')
USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_FLOAT
IMPLICIT NONE
REAL(C_FLOAT), INTENT(OUT) :: f
END SUBROUTINE
END INTERFACE
REAL(C_FLOAT) :: f
!****
CALL do_some_static_stuff(f)
PRINT "(F10.2)", f
END PROGRAM CallCppStaticMethod
[/fortran] Similar forwarding functions, that also have a pointer-to-an-object-of-the-class parameter/C_PTR argument, can be written to call non-static member functions, with fortran just treating the C_PTR as an opaque handle to the class object.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Thank you for the replies - I'll implement the forwarder workaround as described, since all the methods I need to call are static.
Reply
Topic Options
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page