[英]can not correctly pass an array when calling a fortran function from c
我需要从c调用一个fortran函数,参数之一是一个数组,c代码是:
float x[18] = {...};
pot = f_(x);
其中x是具有18个元素的浮点数组,而fortran代码是
function f(x,xc,im) result(pot)
real,dimension(1:18),intent(in)::x
real,dimension(:),optional,intent(in)::xc
integer,optional,intent(in)::im
do i=1,18
write (*,*) x(i)
enddo
...
end function f
fortran函数编写的x数组的元素值与c代码中的元素值不同,有人可以在这里帮我吗? 我使用的编译器是icc和ifort,我使用了ifort来链接* .o文件。 谢谢
具有可选参数的Fortran子例程不能与C互操作。在不传递可选参数时,调用方必须以某种方式发出信号。 一些fortran编译器会传递一个空指针(例如,请参见GNU Fortran邮件列表中的该线程 ),但有些编译器的行为可能完全不同。
无论如何,我强烈建议在Fortran和C之间进行互操作时在Fortran端使用bind(C)
(请参阅此处的一些参数)。 您的Fortran代码如下所示:
module test
use iso_c_binding
implicit none
integer, parameter :: rp = c_float
contains
function ff(xx) result(pot) bind(c)
real(rp), intent(in) :: xx(18)
real(rp) :: pot
integer :: ii
do ii = 1, 18
write(*,*) xx(ii)
end do
pot = -1.0_rp
end function ff
end module test
在C语言中,您会写:
#include <stdio.h>
float ff(float *);
int main()
{
float xx[18], res;
int ii;
for (ii = 0; ii < 18; ++ii) {
xx[ii] = (float) ii;
}
res = ff(xx);
printf("Result: %f\n", res);
}
现在,当您在Fortran端指定optional
时,至少会收到gfortran的错误消息。 奇怪的是,ifort不会给出任何错误消息,但这并不一定意味着它的行为已得到明确定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.