การเรียก subroutine ของ Fortran จาก Mathematica ด้วย NETLink และ DLL

สมมุติว่า subroutine (test.f90) ที่มีคือ

subroutine sum_and_difference(i,j,resultArray)
 implicit none
 integer*4, intent (in) :: i
 integer*4, intent (in) :: j
 integer*4, dimension(2), intent (out) :: resultArray
 resultArray(1) = i + j
 resultArray(2) = i - j
 return
 end subroutine sum_and_difference

compile ด้วย gfortran เพื่อสร้าง DLL

gfortran -c test.f90
gfortran -s -shared -mrtd -o test.dll test.o
จากนั้นในส่วนของ Mathematica ก็ทำตามนี้ครับ
 In[1]:= Needs["NETLink`"]

In[2]:= SetDirectory@NotebookDirectory[]
 Out[2]= "D:\\FU"

In[3]:= $pathToDLL = FileNameJoin[{Directory[], "test.dll"}]
 Out[3]= "D:\\FU\\test.dll"

In[4]:= SumAndDiff = DefineDLLFunction["sum_and_difference_", $pathToDLL, "void", {"Int32*", "Int32*", "Int32[]"}]

In[5]:= results = MakeNETObject[{0, 0}, "System.Int32[]"]

In[6]:= SumAndDiff[10, 20, results]

In[7]:= NETObjectToExpression@results
 Out[7]= {30, -10}

เพิ่มเติมเกี่ยวกับ NetLink
http://www.wolfram.com/learningcenter/tutorialcollection/NETLinkUserGuide/

แนะนำสำหรับคนใช้ Windows ครับ ให้ใช้ gfortran ผ่าน MinGW (http://www.mingw.org/)

%d bloggers like this: