天天看點

.Net(c#) 通過 Fortran 動态連結庫,實作混合程式設計

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 testDLL2

subroutine plus(x,y,z)
    integer x,y,z
    z = x + y
end 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