print_hi.for
subroutine print_hi(n1, n2) bind(C)
implicit none
double precision n1(5)
integer n2
write(*, *) "Double precision array from Fortran: ", n1
write(*, *) "An integer from Fortran: ", n2
return
end
test.cpp
#include <iostream>
extern "C" void print_hi(double *, int *);
using namespace std;
int main()
{
double a[5] = {1., 2., 3., 4., 5.};
int b = 1024;
print_hi(a, &b);
cout << "Hello from C++." << endl;
return 0;
}
在Windows中
编译
gfortran .\print_hi.for -c -fpic
gfortran .\print_hi.o -shared -o libprint_hi.dll
g++ .\test.cpp .\libprint_hi.dll -o test
运行
.\test
检查dll文件函数表
"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x64\dumpbin.exe" /exports "C:\Users\Linwei\Desktop\dll_test\libprint_hi.dll"
在Linux中
编译
gfortran print_hi.for -c -fpic
gfortran print_hi.o -shared -o libprint_hi.so
g++ test.cpp libprint_hi.so -o test -Wl,-R ./
其中 -Wl,-R ./选项表示运行时在当前文件夹搜索动态库
运行
./test
检查so文件函数
nm -D libprint_hi.so
检查可程序文件依赖的动态库
ldd test
本文详细介绍了如何在Windows和Linux环境下,使用C++调用Fortran 77编写的代码。从编译到运行,再到检查动态链接库函数表和程序依赖,一步步解析了整个过程。

6460

被折叠的 条评论
为什么被折叠?



