使用Julia的数组参数调用Fortran子例程

问题描述 投票:4回答:2

我可以调用编译这个fortran代码'test.f90'

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

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

并为Julia创建这个包装函数test.jl:

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

并使用所寻求的输出运行这些命令:

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

但我想返回一个数组而不是一个标量。我想我已经尝试过各种各样的方法,包括在this回答中使用iso_c_binding。但我尝试的一切都会让我看起来像这样的错误:

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

作为一个例子,我想从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

使用注释掉的变体也是一种替代方法,因为从julia调用时只更改参数似乎没有用。

那么如何用朱莉娅的数组调用fortran子程序呢?

arrays fortran julia fortran90 gfortran
2个回答
4
投票

使用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)

0
投票

建议:'&n'将导致较新版本的语法错误无效。并且,使用Ref比Ptr更安全。

你可以尝试:

ccall((:arr_, "./test.so"), Cvoid, (Ref{Int64}, Ref{Int64}), Ref(n), X)
© www.soinside.com 2019 - 2024. All rights reserved.