简体   繁体   English

使用C ++代码从FORTRAN DLL调用函数

[英]Calling a function from a FORTRAN DLL using C++ code

I want to load a fortran dll in C++ code and call a function in the fortran dll. 我想用C ++代码加载一个fortran dll并在fortran dll中调用一个函数。

Following is the code 以下是代码

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

After creation of the foo.dll [fotran dll ] this is the folowing C++ code in visual studio 2012 that I have written to load the fortran dll . 在创建了foo.dll [fotran dll]之后,这是我在Visual Studio 2012中编写的用于加载fortran dll的C ++代码。 and call the function SUB1 in the fortran code 并在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;

}

While running the I am getting the following error: 运行时我收到以下错误:

The program can't start because libgcc_s_dw2-1.dll is missing from your computer. 程序无法启动,因为您的计算机缺少libgcc_s_dw2-1.dll。 Try reinstalling the program to fix this problem. 尝试重新安装该程序以解决此问题。

Is this the correct way of calling the dll from C++ ? 这是从C ++调用dll的正确方法吗? I am very new to this fortran dll . 我对这个fortran dll很新。 Please help me regarding this. 请帮我解决这个问题。

First of all you need to export the function like this... 首先,您需要导出这样的函数...

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

Create the dll using following command 使用以下命令创建dll

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

After that, place the libgcc_s_dw2-1.dll , libgfortran-3.dll and libquadmath-0.dll in the application path of VS. 之后,将libgcc_s_dw2-1.dlllibgfortran-3.dlllibquadmath-0.dll放在VS的应用程序路径中。 OR you can add the PATH to environment. 或者您可以将PATH添加到环境中。

After that, you can call the FORTRAN exposed function from VS like below... 之后,你可以从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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM