Jon*_*röm 5 arrays fortran gfortran fortran90 julia
我可以将编译此fortran代码称为“ test.f90”
subroutine test(g,o)
double precision, intent(in):: g
double precision, intent(out):: o
o=g*g
end subroutine
Run Code Online (Sandbox Code Playgroud)
与
gfortran -shared -fPIC test.f90 -o test.so
Run Code Online (Sandbox Code Playgroud)
并为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
Run Code Online (Sandbox Code Playgroud)
并使用所需的输出运行以下命令:
julia> include("./test.jl")
julia> test(3.4)
11.559999999999999
Run Code Online (Sandbox Code Playgroud)
但是我想返回一个数组而不是一个标量。我想我已经在此答案中尝试了一切,包括使用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
Run Code Online (Sandbox Code Playgroud)
例如,我想从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
Run Code Online (Sandbox Code Playgroud)
使用注释掉的变体也是一种选择,因为从julia调用时仅更改参数似乎没有用。
那么,如何使用Julia的数组调用fortran子例程?
使用时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
Run Code Online (Sandbox Code Playgroud)
与以前一样编译
gfortran -shared -fPIC test.f90 -o test.so
Run Code Online (Sandbox Code Playgroud)
然后在朱莉娅:
n = 10
X = zeros(Int64,n,n) # 8-byte integers
ccall((:arr_, "./test.so"), Void, (Ptr{Int64}, Ptr{Int64}), &n, X)
Run Code Online (Sandbox Code Playgroud)