Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Fortran dll and calling it from C#

Tags:

c#

dll

fortran

I have a function in a Fortran executable and I need to make it a dll file so I can call it's functions from a C# program

      FUNCTION TSAT11(P) 
C     ** IGNORE IMPLEMENTATION **
      TSAT11 = SX*TSAT2(X) + SXL1*TSAT3-273.15 
      RETURN 
      END 

P is a float and the function returns a float

The thing here that I don't know anything in fortran nor calling dlls from C#, so please explain a little more.

I'm using Compaq Visual Fortran and C# 2008.

Thank you for your time.

(If you like you can see the full code Here [It's a program to calculate water and steam properties])

like image 702
workoverflow Avatar asked Apr 25 '12 14:04

workoverflow


2 Answers

Here is an example using single precision floats.

Fortran library contains:

FUNCTION TSAT11(P) 
!DEC$ ATTRIBUTES ALIAS:'TSAT11' :: TSAT11
!DEC$ ATTRIBUTES DLLEXPORT :: TSAT11
!DEC$ ATTRIBUTES VALUE :: P
REAL, INTENT(IN) :: P   
REAL :: TSAT11
    ! Examle calculation
    TSAT11 = P - 273.15
RETURN 
END FUNCTION

With the calling function

class Program
{
    [DllImport("calc.dll")]
    static extern float TSAT11(float P);

    static void Main(string[] args)
    {
        float p = 300f;
        float t = TSAT11(p);
        // returns 26.8500061
    } 
 }

Similarly for an array (must declare the size)

FUNCTION TSAT12(P,N) 
!DEC$ ATTRIBUTES ALIAS:'TSAT12' :: TSAT12
!DEC$ ATTRIBUTES DLLEXPORT :: TSAT12
!DEC$ ATTRIBUTES VALUE :: N
INTEGER, INTENT(IN) :: N
REAL, INTENT(IN) :: P(N)
REAL :: TSAT12
    ! Examle calculation
    TSAT12 = SQRT( DOT_PRODUCT(P,P) )
RETURN 
END FUNCTION

with calling C# code

class Program
{
    [DllImport("calc.dll")]
    static extern float TSAT12(float[] P, int N);

    static void Main(string[] args)
    {
        float[] p2=new float[] { 0.5f, 1.5f, 3.5f };
        float t2=TSAT12(p2, p2.Length);
        //returns 3.84057283
    } 
 }
like image 59
John Alexiou Avatar answered Nov 06 '22 15:11

John Alexiou


You could use P/Invoke. Here's an article which provides an example. As far as compiling your Fortran code into an unmanaged DLL you could create a DLL Project in CVF.

like image 38
Darin Dimitrov Avatar answered Nov 06 '22 14:11

Darin Dimitrov