从FORTRAN调用C代码

时间:2008-12-09 20:46:35

标签: c fortran

鉴于Microsoft FORTRAN 5.1和Microsoft C / C ++ 14.0,以及该版本FORTRAN附带的链接器(必须用于其他依赖项),如何创建C函数并从FORTRAN应用程序调用它?

3 个答案:

答案 0 :(得分:3)

MSDN上有一篇文章,其中包含示例代码:FORTRAN calls to C

答案 1 :(得分:1)

你有两个选择。
1)我可以用例子显示

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 &ltl;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

COMPILE COMMAND

$>g++ -c ctest.c <br/>
$>gfortran -c ftest.f90 <br/>
$>gfortran *.o -lstdc++ -o test_prog <br/>

希望这有帮助

答案 2 :(得分:0)

也许迟到总比没有好。 我记得在视觉工作室1中使用了ms fortran 5.1。我不确定哪个视觉工作室14.0相当,但我认为它是相对较新的而不是13岁。 我认为这种组合不是首发,因为5.1是用于Windows 3的16位编译器。

相关问题