Introduction to MathLink

In many cases, you will find it convenient to communicate with external programs at a high level, and to exchange structured data with them.

On almost all computer systems, Mathematica supports the MathLink communication standard, which allows higher-level communication between Mathematica and external programs. In order to use MathLink, an external program has to include some special source code and a MathLink library, which are usually distributed with Mathematica.

MathLink allows external programs both to call Mathematica, and to be called by Mathematica. "MathLink and External Program Communication" discusses some of the details of MathLink. By using MathLink, you can, for example, treat Mathematica essentially like a subroutine embedded inside an external program. Or you can create a front end that implements your own user interface, and communicates with the Mathematica kernel via MathLink.

You can also use MathLink to let Mathematica call individual functions inside an external program. As described in "MathLink and External Program Communication", you can set up a MathLink template file to specify how particular functions in Mathematica should call functions inside your external program. From the MathLink template file, you can generate source code to include in your program. Then when you start your program, the appropriate Mathematica definitions are automatically made, and when you call a particular Mathematica function, code in your external program is executed.

Install["command"]start an external program and install Mathematica definitions to call functions it contains
Uninstall[link]terminate an external program and uninstall definitions for functions in it

Calling functions in external programs.

This starts the external program , and installs Mathematica definitions to call various functions in it.
In[1]:=
Click for copyable input
Out[1]=
Here is a usage message for a function that was installed in Mathematica to call a function in the external program.
When you call this function, it executes code in the external program.
In[3]:=
Click for copyable input
Out[3]=
This terminates the program.
In[4]:=
Click for copyable input
Out[4]=

You can use MathLink to communicate with many types of programs, including with Mathematica itself. There are versions of the MathLink library for a variety of common programming languages. The J/Link system provides a standard way to integrate Mathematica with Java, based on MathLink. With J/Link you can take any Java class, and immediately make its methods accessible as functions in Mathematica.

New to Mathematica? Find your learning path »
Have a question? Ask support »