【问题标题】:Calling a function from a FORTRAN DLL using C++ code使用 C++ 代码从 FORTRAN DLL 调用函数
【发布时间】:2014-05-12 14:17:23
【问题描述】:

我想在 C++ 代码中加载一个 fortran dll 并在 fortran dll 中调用一个函数。

下面是代码

  SUBROUTINE SUB1()
  PRINT *, 'I am a function '
  END

创建 foo.dll [fotran dll] 后,这是我在 Visual Studio 2012 中编写的用于加载 fortran dll 的以下 C++ 代码。 并在fortran代码中调用函数SUB1

#include <iostream>
#include <fstream>
#include <Windows.h>

using namespace std;  
extern "C" void SUB1();
typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);

int main(void)
{
                LoadLibrary(L"foo.dll");

                PGNSI pGNSI = (PGNSI) GetProcAddress(GetModuleHandle(TEXT("foo.dll")),"SUB1");

                return 0;

}

运行时出现以下错误:

程序无法启动,因为您的计算机中缺少 libgcc_s_dw2-1.dll。 尝试重新安装程序以解决此问题。

这是从 C++ 调用 dll 的正确方法吗? 我对这个 fortran dll 很陌生。请帮我解决这个问题。

【问题讨论】:

  • 请发布您的操作系统、Fortran 和 C++ 编译器。编译器标志也会很有用。尝试搜索 fortran-iso-c-binding 以开始 Fortran-C 互操作性。

标签: c++ dll fortran


【解决方案1】:

首先你需要像这样导出函数...

!fortcall.f90
subroutine Dll1() BIND(C,NAME="Dll1")
implicit none
!DEC$ ATTRIBUTES DLLEXPORT :: Dll1
PRINT *, 'I am a function'
return
end !subroutine Dll1

使用以下命令创建 dll

gfortran.exe -c fortcall.f90
gfortran.exe -shared -static -o foo.dll fortcall.o

之后,将libgcc_s_dw2-1.dlllibgfortran-3.dlllibquadmath-0.dll放在VS的应用路径中。或者您可以将 PATH 添加到环境中。

之后,您可以从 VS 调用 FORTRAN 公开函数,如下所示...

#include <iostream>
#include <Windows.h>

using namespace std;
extern "C" void Dll1();
typedef void(* LPFNDLLFUNC1)();

int main(void)
{
    HINSTANCE hDLL;
    LPFNDLLFUNC1 lpfnDllFunc1;    // Function pointer

    hDLL = LoadLibrary(L"foo.dll");

    if (hDLL != NULL)
    {
        lpfnDllFunc1 = (LPFNDLLFUNC1)GetProcAddress(hDLL,"Dll1");
        if (!lpfnDllFunc1)
        {
            // handle the error
            FreeLibrary(hDLL);
            return -1;
        }
        else
        {
            // call the function
            lpfnDllFunc1();
        }
    }
    return 0;
}

【讨论】:

  • !DEC$ ATTRIBUTES DLLEXPORT 真的在做什么吗?我相信 gfortran 会忽略 !DEC$ 指令。 GCC 默认导出所有符号 AFAIK。 return 语句肯定不是必需的。
  • 确实是老问题,但我正在对此进行调查并发现此主题是最佳结果,但我可以收集到!DEC$ ATTRIBUTES DLLEXPORT 用于 ifort,然后您需要编译源代码编译器工作的 /dll 选项
猜你喜欢
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 2011-07-18
相关资源
最近更新 更多