MathLink Tutorial for Mac OS X
Written by: Chad Armstrong (chad@edenwaith.com)
Last modified: 16 February 2007

MathLink Example Not everyone has the time or know-how to create a powerful mathematical evaluator, but with Wolfram's MathLink technology, they don't need to. MathLink allows a wide variety of platforms and languages to interoperate with Mathematica's back end kernel, which supplies the mathematical muscle for pretty much any type of processing.

This program shows how to connect a Mac OS X application to the Mathematica kernel, from both the command line and Project Builder, and use its processing power to return a mathematical expression. The Student Version of Mathematica 4.2 was used in this tutorial. If you have a different version of Mathematica, make the proper changes when necessary (change 4.2 to 4.1 or 5.0, et cetera). While this tutorial is specific to Mac OS X, parts of it may be useful for other UNIX-like systems.

Installation

Let's start by locating the proper files necessary to be able to integrate Mathlink to your program. Go to the /Applications/Mathematica 4.2/AddOns/MathLink/DeveloperKit/Darwin/ directory. If necessary, right-click or CTRL-click on the Mathematica icon and select Show Package Contents to view the folders within the application.

The Darwin directory contains four directories: CompilerAdditions, Documentation, MathLinkExamples, and PrebuiltExamples. You can explore these various contents to learn more about MathLink, but for now, we are only interested in the CompilerAdditions directory. Go into CompilerAdditions, which will have libML.a, mathlink.framework, mathlink.h, mcc, and mprep. libML.a is the shared library file (similar to a Dynamically Linked Library (DLL) on a Windows system) and mathlink.h is the associated header file, and both of these files are necessary in working with MathLink via the UNIX route. However, this is not particularly the Mac OS X way of doing things. To make things easier, just copy the mathlink.framework folder into your /Library/Frameworks, /System/Library/Frameworks, or ~/Library/Frameworks directory. It does not seem to matter which directory the framework is placed in, as long as you remember where it is when you need it.

If you insist on going via the more UNIX-y route, copy mathlink.h into your /usr/include/ directory and libML.a into /usr/lib/. The sudo command (via the Terminal) is used since the /usr/include and /usr/lib directories are protected by the root user. You will need to type in your password to be able to use sudo.

cd /Applications/Mathematica 4.2.app/AddOns/MathLink/DeveloperKit/Darwin/CompilerAdditions/
sudo cp mathlink.h /usr/include/mathlink.h
Password:
sudo cp libML.a /usr/lib/libML.a
Password:

If you are using Mathematica 5.0, the mathlink.framework has been removed, but the previous MathLink framework should still work properly. Here is a response about the mathlink.framework's disappearance.

The MathLink Framework for OSX in Mathematica 4.2 was experimental and has been removed as of version 5.0. I was unable to find any reference to it in the version 5.0 documentation, but if I am in error please let me know where the references can be found so that I can notify the appropriate people.

The MathLink SDK included with 5.0 is entirely compatible with OS X, so you should not experience any difficulties in using it.

There is some erroneous documentation suggesting that Framework would be included in V5.0 at mathlink.framework is referenced in Addons & Links/Mathlink/System-Specfic Information/Mac OS X/Installing


A copy of the framework can be downloaded here if you want to experiment with it.

Compile & Run

Project Builder
  • Open up and create a new Cocoa application in Project Builder.
  • Go to Project -> Add Frameworks and add the MathLink framework to your project.
  • In which ever file that will use MathLink, add this header: #include <mathlink/mathlink.h> Refer to MLController.m for an example.
  • A sample Cocoa program is available, including the source code, Project Builder files, and interface nib. Download it at MLExample.tgz. Use either Untar, StuffIt Expander™, or the command tar -xvzf MLExample.tgz to uncompress the file.
  • Build iconAs always, to compile and run the project, click on the hammer-monitor icon to build and execute the program.
Command Line
To reduce unnecessary typing, we will add an alias to the mcc compiler to your login file. Open the file ~/.tcshrc with your favorite text editor (pico, vi, emacs, BBEdit, TextWrangler, etc.). Now, add this line:
alias mcc '/Applications/Mathematica\ 4.2.app/AddOns/MathLink/DeveloperKit/Darwin/CompilerAdditions/mcc'

In your source file, remember to add this header: #include "mathlink.h"

Download and evaluate either mltest.c or mltest2.c for small example programs which can be run from the command line. mltest.c is sample code taken from pages 23 and 24 of the MathLink Tutorial, written by Todd Gayley. mltest2.c is similar to mltest.c, except it makes calls to MLPutString instead of MLPutInteger.

To compile: mcc -Wno-long-double -o mltest mltest.c
To run: ./mltest -linkname '/Applications/Mathematica\ 4.2.app/Contents/MacOS/MathKernel -mathlink' -linkmode launch

If you don't want to type in the long command line parameters, you can hard code the parameters into your code.

int argc = 4;
char *argv[5] = {"-linkname",
" '/Applications/Mathematica 4.2.app/Contents/MacOS/MathKernel' -mathlink",
"-linkmode",
"launch",
NULL};

If you are using a version of Mathematica besides version 4.2, remember to make the appropriate changes to the path name.

Source

The MLController.h and MLController.m files are listed, which are available in the MLExample Cocoa program. The MLExample program takes an expression from the user, feeds the string to the Mathematica kernel, and returns a result if the expression was a valid Mathematica expression.

/* MLController.h */

#import <Cocoa/Cocoa.h>

@interface MLController : NSObject
{
    IBOutlet NSTextField *equationField;
    IBOutlet NSTextField *answerField;
}

- (IBAction) calculate : (id) sender;

@end 

/* MLController.m */ #import "MLController.h" #include <mathlink/mathlink.h> @implementation MLController - (IBAction) calculate : (id) sender { float sum = 0; int argc = 4; char *argv[5] = {"-linkname", " '/Applications/Mathematica 4.2.app/Contents/MacOS/MathKernel' -mathlink", "-linkmode", "launch", NULL}; MLINK lp; MLEnvironment env; char *expr; expr = [[equationField stringValue] cString]; env = MLInitialize(NULL); if (env == NULL) { NSBeep(); NSRunAlertPanel(@"Error", @"MathLink Environment could not be initialized.", @"OK", nil, nil); [NSApp terminate:self]; } lp = MLOpen(argc, argv); if (lp == NULL) { NSBeep(); NSRunAlertPanel(@"Error", @"MathLink could not be opened.", @"OK", nil, nil); [NSApp terminate:self]; } MLPutFunction(lp, "EvaluatePacket", 1); MLPutFunction(lp, "ToExpression", 1); MLPutString(lp, expr); MLEndPacket(lp); while (MLNextPacket(lp) != RETURNPKT) MLNewPacket(lp); MLGetFloat(lp, &sum); MLClose(lp); MLDeinitialize(env); [answerField setFloatValue: sum]; } @end
EdenMath ML

EdenMath ML Screenshot EdenMath ML is a standard 4-function calculator which uses the Mathematica kernel as its back end evaluator. EdenMath ML is a slightly more advanced program than the provided MLExample program, which displays what can be done with Mac OS X and the Mathematica kernel. In addition to its Mathematica integration, EdenMath ML implements the NSMatrix, which was not used with the original EdenMath.

Download EdenMath ML to receive the executable file, MathLink tutorial, source code, and project (Project Builder 2.1 Dec 2002 Tools).


Troubleshooting
  • If the end-user system does not have the MathLink framework installed, the application will crash when starting.
  • Even if all references have been removed to MathLink within the code, yet the framework has been added to the project, the application will still crash.
  • As mentioned in the Installation section, the MathLink framework was not included with Mathematica 5.0. Since I do not (yet) have a copy of Version 5, I am assuming that the mathlink.h and libML.a files are used instead of the framework.
  • If the -Wno-long-double option isn't added while compiling from the command line, these warnings, which do not seem to affect the performance of the application, will appear:
    In file included from mltest.c:15:/Applications/Mathematica 4.2.app/AddOns/MathLink/DeveloperKit/Darwin/CompilerAdditions/mathlink.h:1453: warning: use of `long double' type; its size may change in a future release
    /Applications/Mathematica 4.2.app/AddOns/MathLink/DeveloperKit/Darwin/CompilerAdditions/mathlink.h:1453: warning: (Long double usage is reported only once for each file.
    /Applications/Mathematica 4.2.app/AddOns/MathLink/DeveloperKit/Darwin/CompilerAdditions/mathlink.h:1453: warning: To disable this warning, use -Wno-long-double.)
Reference files Wolfram MathLink References
MathLink and Mathematica are registered trademarks of Wolfram Research, Inc.