uns*_*ble 14 fortran wolfram-mathematica mathlink
我有兴趣在Mathematica会话中调用fortran代码.我了解到Mathlink提供了一种方法.但我对C语言知之甚少,对C++没什么了解.有人愿意给我一个详细的例子吗?
我正在使用Mathematica 8,MS Visual Studio 2008和Intel Fortran 11.该系统是Windows 7 Home Premium.
非常感谢!
以下是我使用Windows系统使用gfortan和gcc成功的一个明确示例:
我在Mathlink找到了这个博客Adventures.它有一个具体的例子.我安装了MinGW以便使用gfortran和gcc.安装后,必须设置PATH才能使用gfortran和gcc而不必每次都输入路径.在不重新启动系统的情况下添加PATH的提示:添加PATH后,打开cmd,然后运行set PATH=C:然后关闭cmd,再次打开它时echo %PATH%,您将看到新的路径列表.我按照教程示例addtwo跟踪了适用于Windows的链接博客中的步骤:
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]]
Run Code Online (Sandbox Code Playgroud)
FORTRAN代码addtwo.f
subroutine addtwof(i,j,k)
integer i, j, k
k = i + j
end
Run Code Online (Sandbox Code Playgroud)
C包装器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
Run Code Online (Sandbox Code Playgroud)
模板文件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."
Run Code Online (Sandbox Code Playgroud)