从C传递指针FORTRAN子程序 [英] Passing pointer from C to fortran Subroutine

查看:646
本文介绍了从C传递指针FORTRAN子程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从C调用一个子程序FORTRAN,我可以分配在C和指针传递给Fortran的安全?在子程序中的数组是一个自动数组(X(n最大))。

I am trying to call a fortran subroutine from C, can I allocate in C and pass the pointer to Fortran safely? The array in the subroutine is an automatic array (x(nmax)).

(我分配的X,然后将它传递给FORTRAN)

(I am allocating the x and then passing it to the fortran)

推荐答案

是的。现代的Fortran保证Fortran例程可以从C和副-A-反之亦然调用。这是通过的Fortran ISO_C_BINDING完成。此为二○○三年Fortran语言的一部分,是广泛使用作为一个扩展到Fortran编译器95。有一个在gfortran手册(章节混合编程和内在模块)。作为一个语言功能的文档,此文档不仅仅是为gfortran编译器更加有用。也有这方面的例子在stackover,可以通过FORTRAN-ISO-C结合的标签上找到。

Yes. Modern Fortran guarantees that Fortran routines can be called from C and vice-a-versa. This is done via the Fortran ISO_C_BINDING. This is part of Fortran 2003 and was widely available as an extension to Fortran 95 compilers. There is documentation in the gfortran manual (Chapters "Mixed-Language Programming" and "Intrinsic Modules".) As a language feature, this documentation is more useful than just for the gfortran compiler. There are also examples here on stackover that can be found via the fortran-iso-c-binding tag.

简单code例如:

#include <stdio.h>
#include <stdlib.h>

void F_sub ( float * array_ptr );

int main ( void ) {

   float * array_ptr;

   array_ptr = malloc (8);

   F_sub (array_ptr);

   printf ( "Values are: %f %f\n", array_ptr [0], array_ptr [1] );

   return 0;
}

subroutine F_sub ( array ) bind (C, name="F_sub")

   use, intrinsic :: iso_c_binding
   implicit none

   real (c_float), dimension (2), intent (out) :: array

   array = [ 2.5_c_float, 4.4_c_float ]

end subroutine F_sub

这篇关于从C传递指针FORTRAN子程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆