Calling FORTRAN function or subroutine in DLL from C# code

Calling FORTRAN function or subroutine in DLL from C# code

Intel Fortran does not support generate managed code. To call a FORTRAN function or subroutine from C# code you need build Fortran code into a DLL (Dynamic Link Library), and then use Platform Invoke, a service that enables managed code to call the unmanaged function or subroutines inside the DLL. Platform Invoke service locates and calls unmanaged code as an exported function. It also marshals the call's arguments, such as input and output parameters, integers, strings, arrays, and structures, as needed. To use the service, add below line into your C# code:

 

using System.Runtime.InteropServices;

 

It is recommended to wrap the Fortran function or subroutine in a managed class. Within the class, you define a static method for each Fortran function or subroutine you want to call. Use the DllImportAttribute to identify the DLL and function. Mark the method with the static and extern modifiers. The definition can include additional information, such as the calling convention used in passing method arguments.

 

Example:

 

Fortran Function and Subroutine:

 

INTERFACE

    SUBROUTINE FSUB (A,B)

           !DEC$ ATTRIBUTES DLLEXPORT :: FSUB

        INTEGER :: A,B

END SUBROUTINE

 

    FUNCTION FOO(A)

           !DEC$ ATTRIBUTES DLLEXPORT :: FOO

            INTEGER :: A

            INTEGER :: FOO

    END FUNCTION

END INTERFACE

 

C# Wrapper Class:

 

    public class FortranDllWrap

    {

        // CallingConvention.Cdecl must be used since the stack is

        // cleaned up by the caller in Intel Fortran by default

        //

        [DllImport("FDll.dll", CallingConvention = CallingConvention.Cdecl)]

        public static extern void FSUB(ref int A, ref int B);

        [DllImport("FDll.dll", CallingConvention = CallingConvention.Cdecl)]

        public static extern int FOO(ref int A);

    }   

 

Per informazioni complete sulle ottimizzazioni del compilatore, consultare l'Avviso sull'ottimizzazione