从Julia调用Fortran子例程.数组有效,但整数无效 [英] Calling Fortran subroutine from Julia. Arrays work, but integers don't
问题描述
我有一个简单的Fortran 90程序:
I have this simple Fortran 90 program:
subroutine apc_wrapper(i, j, k)
implicit none
integer*8, intent(in) :: i, j
integer*8, intent(out) :: k
double precision t
k = i + js
end subroutine
编译为共享库
gfortran -O2 -shared -fPIC apc_wrapper.f90 -o apc_wrapper.so
现在,我想从Julia中调用此子例程,并使用所有整数参数,例如
Now, I want to call this subroutine from Julia, with all integer arguments, like this
i = 2
j = 3
k = 0
ccall( (:apc_wrapper_, "./apc_wrapper.so"), Void, (Ptr{Int64}, Ptr{Int64}, Ptr{Int64}), &i, &j, &k)
但是它不起作用. k
不会更改其值,并继续求值为0.
But it won't work. k
won't change its value and keep evaluating to 0.
但是,如果我这样做
i = 2
j = 3
kk = [0]
ccall( (:apc_wrapper_, "./apc_wrapper.so"), Void, (Ptr{Int64}, Ptr{Int64}, Ptr{Int64}), &i, &j, kk)
也就是说,使用数组存储输出,它可以正常工作!调用该子例程后,kk
计算为
That is, use an array to store the output, it works! After calling the subroutine, kk
evaluates to
1-element Array{Int64,1}:
5
我根本没有更改Fortran代码,它甚至都不知道它是在处理数组,只是一块内存.
And I didn't change the Fortran code at all, it didn't even know it was dealing with an array, just a block of memory.
因此,如果Fortran能够读取内存块(i
和j
正确显示为红色),为什么不能写入它们?
So, if Fortran is able to read blocks of memory (i
and j
were properly red) why isn't able to write into them?
我对此没有任何问题.实际上,我想使用数组作为输出,但是这种行为令我感到惊讶.
I don't have any problem with this. Actually, I want to use an array as output but still, this behavior surprised me.
推荐答案
Julia是一种快节奏的开发语言,事实证明&variable
语法已被弃用.
这是执行此操作的正确方法:
Well, Julia is a fast-paced developing language and it turns out that the &variable
syntax is deprecated.
This would be the proper way to do this:
i = 2
j = 3
k = 0
i_ref = Ref{Int64}(i)
j_ref = Ref{Int64}(j)
k_ref = Ref{Int64}(k)
ccall( (:apc_wrapper_, "./apc_wrapper.so"), Void,
(Ref{Int64}, Ref{Int64}, Ref{Int64}),
i_ref, j_ref, k_ref)
,然后k_ref.x
将计算为5
.
这篇关于从Julia调用Fortran子例程.数组有效,但整数无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!