Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Calling Fortran dll from C#

jhlee0301
Beginner
840 Views

Hello guys.

I am familiar with C# but need to import Fortran class library. Not expert in Fortran.

This is most popular example in google but I cannot run it.

Dll_test1.dll is located in bin\Debug of C# project.

When executing debug, there occurs format exception error.

My environment is Visual Studio 2019 and Intel Parallel Studio XE 2020.

I think I miss something in compiler environment.

Please help me to find the solution.

-------------------

Fortran

-------------------

FUNCTION TSAT11(P)

REAL, INTENT(IN) :: P
REAL :: TSAT11
! Examle calculation
TSAT11 = P - 273.15
RETURN
END FUNCTION

 

-----------------------

C#

-----------------------

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
   public static class FortranLib
   {
      private const string _dllName = "Dll_test1.dll";

      [DllImport(_dllName, CallingConvention = CallingConvention.StdCall)]

      public static extern float TSAT11(float P);
   }

   public partial class Form1 : Form
   {

      public Form1()
      {
         InitializeComponent();
      }


      private void btnDoIt_Click(object sender, EventArgs e)
      {
         float p = 300f;

         float t = FortranLib.TSAT11(p);      //<--Error occurs here

      }
   }
}

 

0 Kudos
1 Solution
Steve_Lionel
Honored Contributor III
830 Views

You need to "export" the names of procedures you want to call in the DLL. In Intel Fortran, this is done with an ATTRIBUTES DLLEXPORT directive. I also see that the C# code describes the DLL routine as STDCALL. 

I think the following will do what you need: add the following line to the Fortran code after the FUNCTION statement:

!DEC$ ATTRIBUTES STDCALL, DLLEXPORT, ALIAS:"TSAT11" :: TSAT11

This has a side effect of making the argument P be pass-by-value. 

View solution in original post

0 Kudos
2 Replies
Steve_Lionel
Honored Contributor III
831 Views

You need to "export" the names of procedures you want to call in the DLL. In Intel Fortran, this is done with an ATTRIBUTES DLLEXPORT directive. I also see that the C# code describes the DLL routine as STDCALL. 

I think the following will do what you need: add the following line to the Fortran code after the FUNCTION statement:

!DEC$ ATTRIBUTES STDCALL, DLLEXPORT, ALIAS:"TSAT11" :: TSAT11

This has a side effect of making the argument P be pass-by-value. 

0 Kudos
jhlee0301
Beginner
820 Views

Thank you for the solution.

I still have problem in C# WinForm project so I posted new question.

If you have solution for this please review my posting.

https://community.intel.com/t5/Intel-Fortran-Compiler/Call-Fortran-dll-in-C-Winform/m-p/1204526#M151516

 

0 Kudos
Reply