Some simple examples for calling Fortran from Julia

Author(s): Tero Frondelius

Abstract: Some simple examples for calling Fortran from Julia


In [1]:
f = open("hello.f90","w")
write(f,"subroutine hello(x,z,y)\n")
write(f,"    real*8 x,y\n")
write(f,"""    print *, "Hello World! ", x,y, " testing Jupyter"\n""")
write(f,"end subroutine hello\n")
close(f)

In [2]:
f = open("array.f90","w")
write(f, """
    subroutine array(arr,siz)
        integer*8 siz
        real*8, dimension(siz) :: arr
        do i=1,siz
            print *, "Arr ", arr(i)
        end do
    end subroutine array
        """)
close(f)

In [3]:
f = open("matrix.f90","w")
write(f, """
subroutine matrix(arr,siz)
        integer*8 siz
real*8, dimension(siz,siz) :: arr
        do i=1,siz
            do j=1,siz
                print *, "Arr(",i,",",j,") = ", arr(i,j)
            end do
        end do
end subroutine matrix
        """)
close(f)

In [4]:
run(`gfortran -shared -fPIC -o libhello.so hello.f90 array.f90 matrix.f90`)

In [5]:
tt = 23.; uu = 12.;

In [6]:
t = ccall( (:hello_, "./libhello"), Int64, (Ptr{Float64},Ptr{Void},Ptr{Float64}),&tt,{},&uu)


 Hello World!    23.000000000000000        12.000000000000000       testing Jupyter
Out[6]:
0

In [7]:
test = [6. 5. 4. 3. 2. 1.]
ltest = length(test)


Out[7]:
6

In [8]:
out = ccall( (:array_, "./libhello"), Int64, (Ptr{Float64},Ptr{Int64}),test,&ltest)


 Arr    6.0000000000000000     
 Arr    5.0000000000000000     
 Arr    4.0000000000000000     
 Arr    3.0000000000000000     
 Arr    2.0000000000000000     
 Arr    1.0000000000000000     
Out[8]:
1

In [9]:
mat_test = [1. 2.; 3. 4.]


Out[9]:
2x2 Array{Float64,2}:
 1.0  2.0
 3.0  4.0

In [10]:
l_mat = size(mat_test)[1]


Out[10]:
2

In [11]:
out = ccall( (:matrix_, "./libhello"), Int64, (Ptr{Float64},Ptr{Int64}),mat_test,&l_mat)


 Arr(           1 ,           1 ) =    1.0000000000000000     
 Arr(           1 ,           2 ) =    2.0000000000000000     
 Arr(           2 ,           1 ) =    3.0000000000000000     
 Arr(           2 ,           2 ) =    4.0000000000000000     
Out[11]:
1

In [ ]: