C++调用Fortran程序----动态链接方式

来源:互联网 发布:阿甘起源哥谭网络 编辑:程序博客网 时间:2024/04/28 05:48

参考http://yxbwuhee.blog.sohu.com/143577510.html

一、C++动态调用Fortran DLL

 (1)创建FORTRAN DLL工程,生成forsubs.dll文件供调用。

复制代码
!  forsubs.f90 !!  FUNCTIONS/SUBROUTINES exported from FORSUBS.dll:! FORSUBS      - subroutine !INTEGER*4 FUNCTION Fact (n)   !DEC$ ATTRIBUTES DLLEXPORT::Fact      INTEGER*4 n [VALUE]      INTEGER*4 i, amt      amt = 1      DO i = 1, n        amt = amt * i      END DO      Fact = amt   write(*,*)"Mixed calls succeed!"ENDSUBROUTINE Pythagoras (a, b, c)   !DEC$ ATTRIBUTES DLLEXPORT::Pythagoras      REAL*4 a [VALUE]      REAL*4 b [VALUE]      REAL*4 c [REFERENCE]      c = SQRT (a * a + b * b)END
复制代码

注意:!DEC$ ATTRIBUTES DLLEXPORT::Fact这一句很重要,如果没有这一句的话,C++程序找不到这个接口。

(2)创建win32 console application,调用forsubs.dll。

复制代码
/*     File CMAIN.C   *///C++显式调用FORTRAN动态链接库#include <stdio.h>#include <iostream.h>#include <windows.h>main(){ //声明调用约定 typedef int (_stdcall * FACT)(int n);  typedef void (_stdcall * PYTHAGORAS)(float a, float b, float *c);  //加载动态库文件 HINSTANCE hLibrary=LoadLibrary("forsubs.dll");  if(hLibrary==NULL) {  cout<<"can't find the dll file"<<endl;  return -1; } //获得Fortran导出函数FACT的地址 FACT fact=(FACT)GetProcAddress(hLibrary,"FACT");  if(fact==NULL) {  cout<<"can't find the function file."<<endl;  return -2; } //获得Fortran导出函数PYTHAGORAS的地址 PYTHAGORAS pythagoras=(PYTHAGORAS)GetProcAddress(hLibrary,"PYTHAGORAS");  if(pythagoras==NULL) {  cout<<"can't find the function file."<<endl;  return -2; }    float c;    printf("Factorial of 7 is: %d\n", fact(7));    pythagoras (30, 40, &c);    printf("Hypotenuse if sides 30, 40 is: %f\n", c);    FreeLibrary(hLibrary); //卸载动态库文件    return 0;}
复制代码

 

二、调试Fortran DLL

设置Fortran程序的项目属性,Debugging->Command中,设置为测试程序的EXE文件路径。

 

 

设置Command之后,直接调试Fortran DLL 项目即可。

0 0