我有兴趣在Mathematica会话中调用fortran代码。我了解到Mathlink提供了一种方法。但我对C语言知之甚少,对C ++没什么了解。 有人愿意给我一个详细的例子吗?
我正在使用Mathematica 8,MS Visual Studio 2008和Intel Fortran 11.该系统是Windows 7家庭高级版。
非常感谢!
答案 0 :(得分:7)
以下是一个明确的例子,我成功地使用gfortan和gcc与Windows系统:
我找到了这个博客Adventures in Mathlink。
它有一个具体的例子。我安装了MinGW以便使用gfortran和gcc。安装后,必须设置PATH才能使用gfortran和gcc而不必每次都输入路径。在不重新启动系统的情况下添加PATH的提示:添加PATH后,打开cmd,然后运行set PATH=C:
然后关闭cmd,当您再次打开它时,使用echo %PATH%
,您将看到新的路径列表。我按照教程示例addtwo:
Mathematica代码编写.bat文件并运行它以生成可执行文件
(* Write a .bat file to compile the MathLink template *.tm, FORTRAN codes *.f and
C codes *.c files, and run it to create an executable file. *)
CreateExeF[s_String] :=
Module[{dir, libdir, bindir, BatCode, bat}, dir = NotebookDirectory[];
{libdir, bindir} = StringJoin[
"\"", $InstallationDirectory,
"\\SystemFiles\\Links\\MathLink\\DeveloperKit\\Windows\\CompilerAdditions\\mldev32\\",
#] & /@ {"lib\\", "bin\\"};
BatCode = StringJoin[
"gfortran -c ", #, ".f -o ", #, "f.o
gcc -c ", #, ".c -o ", #, ".o
",
bindir, "mprep.exe\" ", #, ".tm -o ", #, "tm.c
gcc -c ", #, "tm.c -o ", #, "tm.o
gcc ", #, "tm.o ", #, ".o ", #, "f.o ",
libdir, "ml32i3m.lib\" ",
"-lm -lpthread -mwindows -lstdc++ -o ", #
] &;
(* write the .bat file *)
bat = Export[FileNameJoin[{dir, # <> ".bat"}], BatCode[dir <> #],
"string"] &[s];
(* run the .bat file *)
Run[bat]]
FORTRAN代码 addtwo.f
subroutine addtwof(i,j,k)
integer i, j, k
k = i + j
end
C wrapper addtwo.c
#include "mathlink.h"
int addtwo(int i, int j)
{
int res;
addtwof_(&i, &j, &res);
return res;
}
#if WINDOWS_MATHLINK
#if __BORLANDC__
#pragma argsused
#endif
int PASCAL WinMain( HINSTANCE hinstCurrent, HINSTANCE hinstPrevious, LPSTR lpszCmdLine, int nCmdShow)
{
char buff[512];
char FAR * buff_start = buff;
char FAR * argv[32];
char FAR * FAR * argv_end = argv + 32;
hinstPrevious = hinstPrevious; /* suppress warning */
if( !MLInitializeIcon( hinstCurrent, nCmdShow)) return 1;
MLScanString( argv, &argv_end, &lpszCmdLine, &buff_start);
return MLMain( (int)(argv_end - argv), argv);
}
#else
int main(int argc, char* argv[])
{
return MLMain(argc, argv);
}
#endif
模板文件 addtwo.tm 与Todd Gayley教程中的相同。为了完整起见,这里也给出了:
:Begin:
:Function: addtwo
:Pattern: AddTwo[i_Integer, j_Integer]
:Arguments: { i, j }
:ArgumentTypes: { Integer, Integer }
:ReturnType: Integer
:End:
:Evaluate: AddTwo::usage = "AddTwo[i, j] gives the sum of two integer numbers i and j."