从FORTRAN调用C代码
问题描述:
考虑到Microsoft FORTRAN 5.1和Microsoft C/C++ 14.0以及该版本的FORTRAN附带的链接器(必须用于其他依赖项),我如何创建C函数并从中调用它FORTRAN应用程序?从FORTRAN调用C代码
答
你有两个选择。
1)I可与例如
FORTRAN显示
program ftest
use iso_c_bindings
implicit none
interface
function saythis(a) ! should be subroutine if saythis returns void
import :: c_ptr
type(c_ptr), value :: a
end function saythis
end interface
character(len=80), target :: str
type(c_ptr) cstr
integer :: r
str='Hello World From Fortran' // C_NULL_CHAR
cstr=c_loc(str(1:1))
r=saythis(cstr)
C/C++
#ifdef __cpluscplus
#include <l;cstdio>
using namespace std;
#else
#inlcude <stdio.h>
#endif
#ifdef __GNUC__
#define FORT(func) funC## _
#else
#define FORT(func) __stdcall funC## _
#endif
#ifdef __cpluscplus
extern "C" {
#endif
__declspec(dllexport) int FORT(sayit)(char* c)
{
return printf("%s\n",c);
}
#ifdef __cpluscplus
}
#endif
这工作瓦特/ gcc工具。您必须在DLL和Fortran对象代码上使用dumpbin来查看名称是否正确匹配。
另一种方式是相似的:
//This is for gcc toolchain
//you'll have to find the symbol conversion yourself
//I think that Visual Studio converts fortran names
//to ALL CAPS so instead of func => _func you'll need func => FUNC
FORTRAN
program ftest
integer aa,bb,cc
common/vari/aa,bb,cc
aa=7
bb=11
cc=0
call dosomething
call dosomethingelse(aa,bb,cc)
C/C++
#ifdef __cplusplus
extern "C" {
#endif
int _dosomething();
int _dosomethingelse(int*,int*,int*); //all fortran is pass by reference
struct { int aa,bb,cc; } vari;
#ifdef __cplusplus
}
#endif
//function def's go here
//struct vari should be the same memory as common/vari block
编译命令
$>g++ -c ctest.c <br/>
$>gfortran -c ftest.f90 <br/>
$>gfortran *.o -lstdc++ -o test_prog <br/>
希望这会有所帮助
答
也许比从未更晚。 我记得在visual studio 1中使用ms fortran 5.1。我不确定哪个visual studio 14.0等同于我,但我认为它是相对最近的而不是13岁。 我认为这个组合是一个非起动器,因为5.1是windows 3的16位编译器。