Silverfrost Logo About Us | Contact Us
 

Calling .NET methods from Fortran

All .NET methods are contained in classes and to call a method from FTN95 code you must declare it using the FTN95 keyword ASSEMBLY_EXTERNAL. For example,

ASSEMBLY_EXTERNAL(NAME="System.Console.WriteLine") WRITELINE

An FTN95 LIBRARY directive must be included in the code to specify the relevant library. For example, Console.WriteLine is a static method contained in System.dll, and the directive takes the form:

LIBRARY "System.dll"

Within Microsoft Visual Studio .NET references may be added to a solution using the References node in the Solution Explorer as with other .NET projects. To add a reference simply right click the References node and choose Add Reference.

WRITELINE is thus a name for the System.Console.WriteLine method and can be called in the usual manner:

CALL WRITELINE("This will be output to the console")

This approach is appropriate for all static methods but instance methods require a refinement. Before the call you must create an object (i.e. an instance of the class) by using the keywords OBJECT and NEW@ as follows:

ASSEMBLY_EXTERNAL(NAME="System.Net.WebClient.DownloadFile") DOWNLOADFILE
OBJECT("System.Net.WebClient") WEBCLIENT
WEBCLIENT = NEW@("System.Net.WebClient")

The arguments for DOWNLOADFILE in the FTN95 code are the same as those for the method DownloadFile but in Fortran the name of the object is added as the first argument:

CALL DOWNLOADFILE(WEBCLIENT, url, file)

If a .NET method returns a value that can be interpreted as a Fortran INTEGER or REAL value then it can be used in the usual way in an expression or assignment statement. For example the following program uses the method IndexOf from the System.String class and prints the value 2 which is the zero-based index of "ph" in the string "alpha".

ASSEMBLY_EXTERNAL(NAME="System.String.IndexOf") INDEXOF
OBJECT("System.String") STR,SUBSTR
STR=NEW@("System.String","alpha")
SUBSTR=NEW@("System.String","ph")
PRINT*,INDEXOF(STR,SUBSTR)
END

Note that, for clarity, the Fortran aliases above use only upper case letters. However, in your code you may prefer to use mixed case aliases that reflect the external name (FTN95, like all Fortran compilers, converts lower case names to upper case).

 

 

Copyright © 1999-2017 Silverfrost Limited