Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Calling C++ static class methods

Martin__Paul
New Contributor I
2,118 Views

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.

0 Kudos
3 Replies
Wendy_Doerner__Intel
Valued Contributor I
2,118 Views
No there is no way to do this from Fortran. C++ has information hidden from the Fortran compiler.

------

Wendy

Attaching or including files in a post

0 Kudos
IanH
Honored Contributor III
2,118 Views
Because the member function is static, you could always write an ordinary (non-member) function with extern "C" linkage to forward the call.

[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.
0 Kudos
Martin__Paul
New Contributor I
2,118 Views
Thank you for the replies - I'll implement the forwarder workaround as described, since all the methods I need to call are static.
0 Kudos
Reply