【问题标题】:How to call Fortran dll with function as argument in C如何在 C 中以函数作为参数调用 Fortran dll
【发布时间】:2017-03-27 06:16:18
【问题描述】:

我使用 VS2013 和 Intel Visual Fortran,然后用 Fortran 代码制作一个 dll。 在 Fortran 子程序中,它有 3 个参数,“fa”用于传递函数,“a”用于传递数组,“b”用于传递数字。但是当我在VC++中调用它时它不起作用。

更新:

嗯...上面的程序很混乱,所以我重新修改了下面的程序。我创建了一个 fortran dll,它可以传递一个数组来对其元素求和并调用一个 c 函数。

module callctest

use, intrinsic :: iso_c_binding

implicit none
private
public callcfun

contains    

subroutine callcfun(a,b) bind(C,name = "callcfun")
!DEC$ ATTRIBUTES DLLEXPORT :: callcfun 
    implicit none

    real(c_double), dimension(*):: a !receive an array from c
    type(c_funptr), value :: b ! receive a c function 

    real,  parameter::pi=3.14159
    integer :: i
    real :: sum = 0.0

    do i = 1,3          ! sum the array elements
        sum = sum+a(i)
    end do 
    write(*,*) 'total',sum



    return

end subroutine callcfun

end module callctest 

以及它调用fortran子程序的c代码:

#include "stdafx.h"
#include <iostream>

using namespace std;

extern "C" {

    void callcfun( double[], void(f)(int)); //

}

void sayhello(int a){


    cout << "Hi! fortran " <<a<< endl;
}
int main(){

    double a[] = { 10.0, 50, 3.0 };

    callcfun(a, sayhello(50));

    system("pause");
    return 0;

}

在c程序中,函数“sayhello”打印单词“Hi!fortran”和一个整数,我想通过调用fortran编写的“callcfun(array, function)”来调用sayhello函数。

当我在 c 程序中调用 "callcfun(array, function)" if function 像“sayhello”只打印“Hi!fortran”。但是我为 sayhello 函数添加了一个 int 参数,以便它打印单词“Hi!fortran”和一个整数参数。函数“callcfun”未成功执行。

错误列表:

错误 1 ​​错误 C2664: 'void callcfun(double [],void (__cdecl *)(int))' : 无法将参数 2 从 'void' 转换为 'void (__cdecl *)(int)' c:\users \emlab\documents\visual studio 2013\projects\vc++\call_for_ex\call_for_ex\call_for_ex.cpp 21 1 call_for_ex

2 IntelliSense:“void”类型的参数与参数不兼容 键入“void (*)(int)” c:\Users\EMlab\Documents\Visual Studio 2013\Projects\VC++\call_for_ex\call_for_ex\call_for_ex.cpp 21 14 call_for_ex

错误显示c函数中的问题,如何将c函数传回fortran dll然后在fortran中调用它?

【问题讨论】:

  • 什么是“它不起作用”?崩溃,错误的结果?哪些结果?任何错误信息?哪些消息?
  • 我在上面添加了错误信息。也许我的程序不是很清楚我想要什么。我的对象在 arraysum 中传递一个 c 函数,然后将它传递给 fortran 程序。

标签: c++ visual-c++ fortran fortran-iso-c-binding


【解决方案1】:

要使 Fortran 过程具有互操作性,BIND(C) 属性是必需的。两个 Fortran 过程都缺少此属性。

对于要从 Windows 上的 DLL 导出的过程,过程的符号名称最终必须提供给链接器。 (有三种方法:编译器将源指令传递到目标代码中(根据与arraysum 过程一起使用的!DEC$ ATTRIBUTES DLLEXPORT 指令),通过在模块定义文件中列出过程名称或通过在链接器命令行上的 /EXPORT 之后列出名称 - 我假设没有使用后两种方法。)鉴于指定一个过程的源指令方法已用于其中一个过程 (arraysum)导出时,该方法也应该用于需要导出的其他过程 (fcn)。

对于具有 C 链接的 C++ 函数,必须使用 extern "C" 声明它。在 C++ 代码中,fcn 没有这样的声明。 (没有任何 fcn 声明意味着不应该编译 C++ 代码。)

在从 C++ 代码构建 exe 时,必须将链接器在构建 Fortran DLL 时生成的导入库 (.lib) 提供给链接器。通常这是在 Visual Studio 中通过在链接器 > 输入属性页上提供导入库作为“附加依赖项”来完成的。

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 2017-11-08
    • 2021-02-11
    • 1970-01-01
    • 2015-06-13
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多