Since the use of both Fortran and C routines is sometimes needed in application codes, we provide two PETSc commands to facilitate passing PETSc objects (such as Mat and SLES) between the two languages. These routines must be called within any C/C++ routines that pass/receive PETSc objects to/from Fortran routines to ensure that the objects are properly handled, since Fortran treats PETSc objects simply as integers.
Different machines have different methods of naming Fortran routines called from C (or C routines called from Fortran). Most Fortran compilers change all the capital letters in Fortran routines to small. On some machines, the Fortran compiler appends an underscore to the end of each Fortran routine name; for example, the Fortran routine Dabsc() would be called from C with dabsc_(). Other machines change all the letters in Fortran routine names to capitals.
PETSc provides two macros (defined in C/C++) to help write
portable code that mixes C/C++ and Fortran. They are
HAVE_FORTRAN_UNDERSCORE and HAVE_FORTRAN_CAPS
,
which are defined in the file ${}PETSC_DIR/bmake/${}PETSC_ARCH/petscconf.h.
The macros are used, for example, as follows:
#if defined(HAVE_FORTRAN_CAPS) #define dabsc_ DABSC #elif !defined(HAVE_FORTRAN_UNDERSCORE) #define dabsc_ dabsc #endif ..... dabsc_(&n,x,y); /* call the Fortran function */Another useful routine for mixed language programming with PETSc is PetscInitializeFortran(), which should be used if one is using a C main program that calls Fortran routines that in turn call PETSc routines. In this case, PetscInitializeFortran() should be called from C after the call to PetscInitialize() to initialize some of the default viewers, communicators, etc. for use in the Fortran. PetscInitializeFortran() is not needed if a user's main program is written in Fortran; in this case, just calling PetscInitialize() in the main program is sufficient.