Calling Fortran From C Sharp

Fortran DLL and ExcelIf you are involved in a project thats calls legacy Fortran code from c sharp, then this is one post (Accessing Fortran Legacy DLL in C#) by Ranjeet Sharma that you shouldn’t miss.

These are few important considerations from the post

Important Considerations:

    The FORTRAN DLL cannot be accessed from C# using Add Reference as it is not a managed DLL. It can be accessed only through P/Invoke syntax.
    When doing mixed-language programming with FORTRAN and C# we must be concerned with data types, because each language handles them differently.
    Along with the Data type differences there is a marked difference between C# and FORTRAN in the way the Memory is allocated to the Arrays.C# used a Row Major memory allocation i.e. data of a row is stored in Contiguous memory locations however Fortran uses a Column Major memory allocation i.e. data of a column is stored in contiguous memory locations. So when sending arrays from C# to FORTRAN we need to transpose the array so that FORTRAN understands the data send to it.
    In C# we distinguish between parameters as being passed either by reference or by value. In FORTRAN all parameters are passed by reference only. Hence every scalar parameter to a FORTRAN routine has to be qualified by the keyword ref. This does not apply to arrays as arrays are passed by reference in C#.
    Complex type as such does not exist in C#. A complex number Z may be represented as an ordered pair of real numbers consisting of the real part of Z and the imaginary part of Z. In FORTRAN this is exactly how a complex type is stored .Specifically we may use a C# double array to hold the real and imaginary parts (in that order) of complex numbers and pass this into the FORTRAN DLL to represent a complex array or complex number.
    If FORTRAN DLL subroutine uses a character Array then to call that subroutine in C# we need to pass two parameters for that First parameters will actually hold the Character content and second parameters will hold the length of the string builder.

For the picture on data type information and sample code visit the original post.

Most of considerations listed here are applicable for mixing Fortran with any other language, be it Java, Python, VBA or C++.

One thought on “Calling Fortran From C Sharp

  1. Pingback: Mixing debug and release libraries in Visual Studio |

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s