【问题标题】:C Wrapper Calling Fortran Functions调用 Fortran 函数的 C 包装器
【发布时间】:2015-05-19 06:31:29
【问题描述】:

我正在尝试编写一个 C 包装器来调用 Fortran 模块中的一组函数。我从一些基本的东西开始,但我错过了一些重要的东西。

我尝试过附加/前置不同数量的下划线。我也尝试过使用 gcc 而不是 gfortran 链接。我在下面显示的内容给出了最简单的错误。

我正在使用运行 Yosemite 10.10.3、GNU Fortran 5.1.0 和 Xcode 附带的 C 编译器的 Mac。

ma​​in.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
$ 

【问题讨论】:

  • 错误提示您混合 32 位和 64 位代码?
  • 始终使用标签fortran,仅当您想强调您不想要任何较新的标准版本时才使用各个版本的标签。

标签: c fortran gfortran fortran-iso-c-binding


【解决方案1】:

你必须将 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

【讨论】:

  • 谢谢你,弗拉基米尔。您的解决方案有效。在 Fortran 函数 change_integer 中,参数“power”是本地的。绑定到 C 是否仍然必要,或者将所有声明绑定到 C 只是一种良好的编程习惯?
  • 我想你是在向我提问。是的,您可以避免绑定幂变量,因为它是本地的。我以前在编写包装器时总是使用绑定。避免忘记强制绑定是个人规则。请将答案设置为正确,以免其他人浪费时间。
  • 这个问题适合任何有经验的人。我自己测试过,发现它不是必需的,但我同意你的推理。感谢 LP 的回复和您在管理我的问题方面的指导。
猜你喜欢
  • 1970-01-01
  • 2012-06-18
  • 2016-01-01
  • 2016-03-25
  • 1970-01-01
  • 2017-09-13
  • 2012-12-17
  • 1970-01-01
  • 2016-07-29
相关资源
最近更新 更多