.Net(c#) 通过 Fortran 动态链接库,实现混合编程

来源:互联网 发布:keynote 模版 知乎 编辑:程序博客网 时间:2024/04/30 02:32
c# 与 Fortran 混合编程解决方案主要有两种:

1. 进程级的交互:在 Fortran 中编译为控制台程序,.Net 调用(System.Diagnostics.Process),然后使用 Process 的 StandardOutput 属性读取控制台输出内容,显示到界面上。
2. 代码级的交互:在 Fortran 中编译为动态链接库,.Net 调用此非托管 DLL 。

本文为第二种方案初级介绍,并只涉及到数值传递,以一个简单的返回相加数值作为实例。


一、打开CVF,新建 fortran dynamic link library ,命名为 testDLL.dll ,新建源文件,写入以下代码:编译生成 DLL 文件。

subroutine testDLL2(a,b,c)    implicit none    !dec$ attributes dllexport::testDLL2    !dec$ attributes alias:"testDLL2"::testDLL2    !dec$ attributes reference::c    !dec$ attributes value::a,b        integer a,b,c    call plus(a,b,c)    end subroutine testDLL2subroutine plus(x,y,z)    integer x,y,z    z = x + yend subroutine plus

其中,隐含在注释中的命令:

!dec$ attributes dllexport::testDLL2

申明此函数可对外公开使用

!dec$ attributes alias:"testDLL2"::testDLL2

 限定子例程名为testDLL2的混合书写形式

!dec$ attributes reference::c

使用 reference 将 c 定义为引用传递方式

        !dec$ attributes value::a,b

使用 value 将 a,b 定义为值传递方式

可以注意到的是此处调用的 plus 子例程无须有上述命令


二、在 VS 中新建 项目-类库 ,命名空间为 PlaceFortran ,写入如下代码,将编译好的 fortran DLL 文件放置 bin/debug 文件夹下

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.InteropServices;namespace PlaceFortran{    public class ClassTest    {        [DllImport("testDLL.dll")]        public static extern void testDLL2(int x, int y, ref int c);//c为地址传递          public int testSub(int x, int y)        {            int p;            testDLL2(x, y, ref p);                        return p;        }    }}

至此,可以在界面层调用这个函数进行相加计算

            ClassTest c = new ClassTest();            int i = c.testSub(22,23);//返回相加数为45


	
				
		
原创粉丝点击