问题描述
我在 Fortran 可执行文件中有一个函数,我需要将它变成一个 dll 文件,以便我可以从 C# 程序调用它的函数
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 是一个浮点数,函数返回一个浮点数
P is a float and the function returns a float
这里的事情我对 fortran 一无所知,也不知道从 C# 调用 dll,所以请多解释一下.
The thing here that I don't know anything in fortran nor calling dlls from C#, so please explain a little more.
我使用的是 Compaq Visual Fortran 和 C# 2008.
I'm using Compaq Visual Fortran and C# 2008.
感谢您的宝贵时间.
(如果您愿意,可以查看完整代码此处 [这是一个计算水和蒸汽特性的程序])
(If you like you can see the full code Here [It's a program to calculate water and steam properties])
推荐答案
这是一个使用单精度浮点数的示例.
Here is an example using single precision floats.
Fortran 库包含:
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
带调用函数
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
通过调用C#
代码
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
}
}
这篇关于制作 Fortran dll 并从 C# 调用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!