C封装器调用Fortran函数

4
我正在尝试编写一个C封装器,以调用Fortran模块中的一组函数。我从基本的东西开始,但是我缺少重要的东西。
我尝试添加/预置不同数量的下划线。我还尝试使用gcc而不是gfortran进行链接。下面显示的内容给出了最简单的错误。
我正在使用运行Yosemite 10.10.3的Mac,GNU Fortran 5.1.0和Xcode附带的C编译器。
main.c
#include "stdio.h"

int main(void) 
{
    int a;
    float b;
    char c[30];
    extern int _change_integer(int *a);

    printf("Please input an integer: ");
    scanf("%d", &a);

    printf("You new integer is: %d\n", _change_integer(&a));

    return 0;
}

intrealstring.f90

module intrealstring
use iso_c_binding
implicit none

contains

integer function change_integer(n)
    implicit none

    integer, intent(in) :: n
    integer, parameter :: power = 2

    change_integer = n ** power
end function change_integer

end module intrealstring

以下是我的编译方式和错误信息:

$ gcc -c main.c
$ gfortran -c intrealstring.f90
$ gfortran main.o intrealstring.o -o cwrapper
Undefined symbols for architecture x86_64:
  "__change_integer", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
$ 

1
错误提示您是否混合了32位和64位代码? - cjb110
始终使用标签[tag:fortran],仅在您想强调不需要任何更新的标准版本时才使用各个版本的标签。 - Vladimir F Героям слава
1个回答

4

您需要将Fortran绑定到C语言:

module intrealstring
use iso_c_binding
implicit none

contains

integer (C_INT) function change_integer(n) bind(c)
    implicit none

    integer (C_INT), intent(in) :: n
    integer (C_INT), parameter :: power = 2

    change_integer = n ** power
end function change_integer

end module intrealstring

您的c文件需要做以下修改:
#include "stdio.h"

int change_integer(int *n);

int main(void) 
{
    int a;
    float b;
    char c[30];

    printf("Please input an integer: ");
    scanf("%d", &a);

    printf("You new integer is: %d\n", change_integer(&a));

    return 0;
}

你可以这样做:

$ gcc -c main.c
$ gfortran -c intrealstring.f90
$ gfortran main.o intrealstring.o -o cwrapper

谢谢,Vladimir。你的解决方案有效。在Fortran函数change_integer中,“power”参数是局部的。绑定到C仍然必要还是将所有声明绑定到C只是良好的编程实践? - leoleson
我认为你在向我提问。是的,你可以避免绑定power变量,因为它是局部的。当我编写包装器时,我通常会使用绑定。这是一个个人规则,以避免忘记必须绑定的情况。请将答案设置为正确,以避免其他人浪费时间。 - LPs
问题是针对有经验的任何人的。我自己测试过了,发现不是必需的,但我同意你的推理。谢谢LPs回复和指导我管理我的问题。 - leoleson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接