Coding Requirements for Sharing Procedures in DLLs

A dynamic-link library (DLL) contains one or more subprograms that are compiled, linked and stored separately from the applications using them.

Coding requirements include using the cDEC$ ATTRIBUTES DLLIMPORT and DLLEXPORT compiler directives. Variables and routines declared in the main program and in the DLL are not visible to each other unless you use DLLIMPORT and DLLEXPORT.

This section discusses aspects of sharing subprogram procedures (functions and subroutines) in a Fortran DLL.

To export and import each DLL subprogram:

  1. Within your Fortran DLL, export each subprogram that will be used outside the DLL. Add a cDEC$ ATTRIBUTES DLLEXPORT directive to declare that a function, subroutine, or data is being exported outside the DLL. For example:
      SUBROUTINE ARRAYTEST(arr)
      !DEC$ ATTRIBUTES DLLEXPORT :: ARRAYTEST
         REAL(4) arr(3, 7)
         INTEGER i, j
         DO i = 1, 3
            DO j = 1, 7
               arr (i, j) = 11.0 * i + j
            END DO
         END DO
      END SUBROUTINE
    
  2. Within your Fortran application, import each DLL subprogram. Add a cDEC$ ATTRIBUTES DLLIMPORT directive to declare that a function, subroutine, or data is being imported from outside the current image. For example:
      INTERFACE
         SUBROUTINE ARRAYTEST (rarray)
         !DEC$ ATTRIBUTES DLLIMPORT :: ARRAYTEST
            REAL rarray(3, 7)
         END SUBROUTINE ARRAYTEST
      END INTERFACE
    

    The DLLEXPORT and DLLIMPORT options (for the cDEC$ ATTRIBUTES directive) define a DLL's interface.

    The DLLEXPORT property declares that functions or data are being exported to other images or DLLs, usually eliminating the need for a Linker module definition (.DEF) file to export symbols for the functions or subroutines declared with DLLEXPORT. When you declare a function, subroutine, or data with the DLLEXPORT property, it must be defined in the same module of the same program.

    A program that uses symbols defined in another image (such as a DLL) must import them. The DLL user needs to link with the import LIB file from the other image and use the DLLIMPORT property inside the application that imports the symbol. The DLLIMPORT option is used in a declaration, not a definition, because you do not define the symbol you are importing.

  3. Build the DLL and then build the main program, as described in Building and Using Dynamic-Link Libraries.

Fortran and C applications can call Fortran and C DLLs provided the calling conventions are consistent (see Programming with Mixed Languages, especially Visual Fortran/Visual C++ Mixed-Language Programs).

Visual Basic applications can also call Fortran functions and subroutines in the form of DLLs (see Programming with Mixed Languages, especially Calling Visual Fortran from Visual Basic).

For more information: