Call Fortran routines with array arguments from Julia

I can force compilation of this code fortran 'test.f90'

subroutine test(g,o)
double precision, intent(in):: g
double precision, intent(out):: o
o=g*g
end subroutine

with

gfortran -shared -fPIC test.f90 -o test.so

and create this wraper test.jl function for Julia:

function test(s)
  res=Float64[1]
  ccall((:test_, "./test.so"), Ptr{Float64}, (Ptr{Float64}, Ptr{Float64}), &s,res);
  return res[1]
end

and run this command with the desired output:

julia> include("./test.jl")    
julia> test(3.4)
11.559999999999999

But I want to return an array instead of a scalar. I think I tried everything, including using iso_c_binding, in this answer. But all I'm trying to do is throwing errors to me:

ERROR: MethodError: `convert` has no method matching convert(::Type{Ptr{Array{Int32,2}}}, ::Array{Int32,2})
This may have arisen from a call to the constructor Ptr{Array{Int32,2}}(...),
since type constructors fall back to convert methods.
Closest candidates are:
  call{T}(::Type{T}, ::Any)
  convert{T}(::Type{Ptr{T}}, ::UInt64)
  convert{T}(::Type{Ptr{T}}, ::Int64)
  ...
 [inlined code] from ./deprecated.jl:417
 in unsafe_convert at ./no file:429496729

As an example, I would like to name the following code from julia:

subroutine arr(array) ! or  arr(n,array)
implicit none
integer*8, intent(inout) :: array(:,:)
!integer*8, intent(in) :: n
!integer*8, intent(out) :: array(n,n)
integer :: i, j

do i=1,size(array,2) !n
    do j=1,size(array,1) !n
        array(i,j)= j+i
    enddo
enddo
end subroutine

Using the comment option is also an alternative, as changing the name may not be useful when calling from julia.

So how do I call fortran routines with arrays from Julia?

+4
2

ccall Julia , , .

test.f90 :

subroutine arr(n,array)
implicit none
integer*8, intent(in) :: n
integer*8, intent(out) :: array(n,n)
integer :: i, j

do i=1,size(array,2) !n
    do j=1,size(array,1) !n
        array(i,j)= j+i
    enddo
enddo
end subroutine

, ,

gfortran -shared -fPIC test.f90 -o test.so

:

n = 10
X = zeros(Int64,n,n) # 8-byte integers
ccall((:arr_, "./test.so"), Void, (Ptr{Int64}, Ptr{Int64}), &n, X)
+4

: '& n' . Ref , Ptr.

ccall ((: arr_, "./test.so"), Cvoid, (Ref {Int64}, Ref {Int64}), Ref (n), X)

0

Source: https://habr.com/ru/post/1656641/


All Articles