Hi all,
I am trying to call Fortran from Julia, but there’re some issues.
1. Fortran constants
cglobal works fine when calling Fortran static module variables, but it cannot find Fortran constants. For example, here is a simple Fortran module:
module simpleModule
implicit none
integer, parameter:: hparam = 10
integer :: h1 = 1
real :: r(2) = [1.0,2.0]
real, allocatable :: s(:)
contains
function foo(x)
integer :: foo, x
foo = x * 2
end function foo
subroutine init_var
integer :: i
if(.not.allocated(s)) then
allocate(s(10))
else
write(*,*) 's has already been allocated!'
endif
do i=1,10
s(i) = i
enddo
write(*,*) s
end subroutine init_var
subroutine double_var(x)
real, intent(inout):: x(:)
x = x * 2
write(*,*) x
end subroutine double_var
end module simplemodule
which can be compile into a dynamic library with the following command:
gfortran simplemodule.f95 -o simplemodule.so -shared -fPIC
Then in Julia,
# import integer
a = cglobal((:__simplemodule_MOD_h1, "./simplemodule.so"), Int32)
b = unsafe_load(a)
# import integer array
a = cglobal((:__simplemodule_MOD_r, "./simplemodule.so"), Float32)
# method 1
b = [unsafe_load(a,i) for i in 1:2]
# method 2
b = unsafe_wrap(Array{Float32,1}, a, 2)
works fine, but
# import constant integer error?
a = cglobal((:__simplemodule_MOD_hparam, "./simplemodule.so"), Int32)
returns error, saying that no such variable is found in the library. How does Fortran deal with constant parameters, and is there a way to get the constant value in Julia?
2. Fortran allocatable arrays
The follow Julia calls can successfully allocate, initialize, and modify the Fortran array s:
ccall((:__simplemodule_MOD_init_var, "./simplemodule.so"), Cvoid, ())
s = cglobal((:__simplemodule_MOD_s, "./simplemodule.so"), Float32)
ccall((:__simplemodule_MOD_double_var, "./simplemodule.so"), Cvoid,
(Ptr{Float64},), s)
However, when I tried to use the pointer to get the values of s, it showed wrong values:
b = unsafe_wrap(Array{Float32,1}, s, 10) # This is not working!
Why is that? Can I get the correct values through other methods?
Thanks!