Examples of Fortran/Visual Basic Programs

The following brief code demonstrates the interface for a Fortran subroutine and function (free-form Fortran source):

  1. In the visual development environment, create a new project of type Fortran Dynamic-Link Library. Name the project FCALL.
  2. Create a new free-form source file (Project menu, Add to Project, New) for the project named FCALL.F90 with the following code:
     ! Fortran Code  establishing subroutine
     ! Computes the MOD of R1 and 256.0 and stores the
     ! result in the argument NUM
    
      SUBROUTINE FortranCall (r1, num)
    ! Specify that the routine name is to be made available to callers of the ! DLL and that the external name should not have any prefix or suffix !DEC$ ATTRIBUTES DLLEXPORT :: FortranCall !DEC$ ATTRIBUTES ALIAS:'FortranCall' :: FortranCall REAL,INTENT(IN) :: r1 ! Input argument REAL,INTENT(OUT) :: num num = MOD (r1, 256.0) END SUBROUTINE
  3. Build the Fortran DLL as described in Building and Using Dynamic-Link Libraries.
  4. Start Visual Basic and create a new Standard EXE project:
  5. Double-click the Command button on the form - a code window will appear. Fill in the code so that it looks like this:
       Private Sub Command1_Click()
       r1 = 456.78
       Call FortranCall(r1, Num)
       Text1.Text = Str$(Num)
       End Sub
    
  6. Select Project..Add Module and click Open to create a new module. Add the following code to the module:
       Declare Sub FortranCall Lib"c:\MyProjects\Fcall\Debug\Fcall.dll"
                (r1 As Single, Num As Single)
    

    Replace the filename with the location of the Fortran DLL, if it is different.

  7. Run the Basic program by pressing F5. Click the Do it! button. The Fortran routine will be called to compute the modulus, returning the result to the Basic code. The Basic code will then convert the result to a string and display it in the text box.

Visual Basic, like Fortran, passes numeric values (such as integers and reals) by reference, so it is not necessary to change the passing mechanism on either side. The ALIAS attribute is required because Visual Basic, even though it uses the STDCALL calling mechanism, does not "decorate" routine names with the @n suffix. If the Fortran routine were also to be called by other Fortran code, it would be appropriate to use the Alias option on the Basic side to name it with the proper suffix.