Calling External Code from Oct-Files (GNU Octave (version 9.4.0))

#### A.1.9 Calling External Code from Oct-Files ¶

Linking external C code to Octave is relatively simple, as the C functions can easily be called directly from C++. One possible issue is that the declarations of the external C functions may need to be explicitly defined as C functions to the compiler. If the declarations of the external C functions are in the header `foo.h`, then the tactic to ensure that the C++ compiler treats these declarations as C code is

    #ifdef __cplusplus
    extern "C"
    {
    #endif
    #include "foo.h"
    #ifdef __cplusplus
    }  /* end extern "C" */
    #endif

When calling functions that are implemented in Fortran code, some pecularities have to be taken into account. Symbol names in Fortran are case-insensitive, and depending on the used Fortran compiler, function names are either exported with all lower-case or with all upper-case characters. Additionally, some compilers append none, one or two underscores "`_`" at the end of exported function names. This is called "name-mangling".

Octave supplies macros that allow writing code that automatically handles the name-mangling for a number of different Fortran compilers. These macros are `F77_FUNC` and `F77_FUNC_`. The former should be used for Fortran functions that do not contain any underscores in their name. The latter should be used for Fortran functions with underscores in their names. Both macros take two arguments: The first is the Fortran function name in all lower-case characters. The second is the same Fortran function name in all upper-case characters.

Additionally to the name-mangling, different compilers are using different calling conventions for some types. Octave defines the following preprocessor macros to allow writing code that can be used with different Fortran calling conventions.

Note that we don’t attempt to handle Fortran functions, we always use subroutine wrappers for them and pass the return value as an extra argument.

Use the following macros to pass character strings from C to Fortran:

      F77_CHAR_ARG(x)
      F77_CONST_CHAR_ARG(x)
      F77_CXX_STRING_ARG(x)
      F77_CHAR_ARG_LEN(l)
      F77_CHAR_ARG_DECL
      F77_CONST_CHAR_ARG_DECL
      F77_CHAR_ARG_LEN_DECL

Use the following macros to write C-language functions that accept Fortran-style character strings:

      F77_CHAR_ARG_DEF(s, len)
      F77_CONST_CHAR_ARG_DEF(s, len)
      F77_CHAR_ARG_LEN_DEF(len)
      F77_CHAR_ARG_USE(s)
      F77_CHAR_ARG_LEN_USE(s, len)

Use the following macros for Fortran types in C++ code:

`F77_INT4`

  Equivalent to Fortran `INTEGER*4` type

`F77_DBLE`

  Equivalent to Fortran `DOUBLE PRECISION` type

`F77_REAL`

  Equivalent to Fortran `REAL` type

`F77_CMPLX`

  Equivalent to Fortran `COMPLEX` type

`F77_DBLE_CMPLX`

  Equivalent to Fortran `DOUBLE COMPLEX` type

`F77_LOGICAL`

  Equivalent to Fortran `LOGICAL` type

`F77_RET_T`

  Return type of a C++ function that acts like a Fortran subroutine.

Use the following macros to return from C-language functions that are supposed to act like Fortran subroutines. `F77_NORETURN` is intended to be used as the last statement of such a function that has been tagged with a `"noreturn"` attribute.

      F77_RETURN(retval)
      F77_NORETURN(retval)

The underlying Fortran code should use the `XSTOPX` function to replace the Fortran `STOP` function. `XSTOPX` uses the Octave exception handler to treat failing cases in the Fortran code explicitly. Note that Octave supplies its own replacement BLAS `XERBLA` function, which uses `XSTOPX`.

The following example shows the inclusion of a Fortran function in an oct-file, where the C++ wrapper is

    #include <octave/oct.h>
    #include <octave/f77-fcn.h>

    extern "C"
    {
      F77_RET_T
      F77_FUNC (fortransub, FORTRANSUB)
        (const F77_INT&, F77_DBLE*, F77_CHAR_ARG_DECL F77_CHAR_ARG_LEN_DECL);
    }

    DEFUN_DLD (fortrandemo, args, , "Fortran Demo")
    {
      if (args.length () != 1)
        print_usage ();

      NDArray a = args(0).array_value ();

      double *av = a.fortran_vec ();
      octave_idx_type na = a.numel ();

      OCTAVE_LOCAL_BUFFER (char, ctmp, 128);

      F77_FUNC (fortransub, FORTRANSUB)
                (na, av, ctmp F77_CHAR_ARG_LEN (128));

      return ovl (a, std::string (ctmp));
    }

and the Fortran function is

          subroutine fortransub (n, a, s)
          implicit none
          character*(*) s
          real*8 a(*)
          integer*4 i, n, ioerr
          do i = 1, n
            if (a(i) .eq. 0d0) then
              call xstopx ('fortransub: divide by zero')
            else
              a(i) = 1d0 / a(i)
            endif
          enddo
          write (unit = s, fmt = '(a,i3,a,a)', iostat = ioerr)
         $       'There are ', n,
         $       ' values in the input vector', char(0)
          if (ioerr .ne. 0) then
            call xstopx ('fortransub: error writing string')
          endif
          return
          end

This example demonstrates most of the features needed to link to an external Fortran function, including passing arrays and strings, as well as exception handling. Both the Fortran and C++ files need to be compiled in order for the example to work.

    mkoctfile fortrandemo.cc fortransub.f
    [b, s] = fortrandemo (1:3)
    ⇒
      b = 1.00000   0.50000   0.33333
      s = There are   3 values in the input vector
    [b, s] = fortrandemo (0:3)
    error: fortrandemo: fortransub: divide by zero