manpagez: man pages & more
info octave
Home | html | info | man
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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 the declarations of the external C functions might 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 manner in which 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

Calling Fortran code however can pose some difficulties. This is due to differences in the manner in compilers treat the linking of Fortran code with C or C++ code. Octave supplies a number of macros that allow consistent behavior across a number of compilers.

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.

If the underlying code calls XSTOPX, then the F77_XFCN macro should be used to call the underlying fortran function. The Fortran exception state can then be checked with the global variable f77_exception_encountered. If XSTOPX will not be called, then the F77_FCN macro should be used instead to call the Fortran code.

There is no harm in using F77_XFCN in all cases, except that for Fortran code that is short running and executes a large number of times, there is potentially an overhead in doing so. However, if F77_FCN is used with code that calls XSTOP, Octave can generate a segmentation fault.

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

and the fortran function is

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. An example of the behavior of this function is

 
[b, s] = fortdemo (1:3)
⇒
  b = 1.00000   0.50000   0.33333
  s = There are   3 values in the input vector
[b, s] = fortdemo(0:3)
error: fortsub:divide by zero
error: exception encountered in Fortran subroutine fortsub_
error: fortdemo: error in fortran

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]
© manpagez.com 2000-2024
Individual documents may contain additional copyright information.