You will find a complete, step by step description of how to write such a program here. Here's a small test program that adds 42 and 137, written by following the tutorial closely:
/* mlcall.c */
#include <mathlink.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
MLENV env;
MLINK link;
int errno;
int packet;
env = MLInitialize(0);
/* consider using MLOpenString instead here: */
link = MLOpenArgcArgv(env, argc, argv, &errno);
MLActivate(link);
/* send 42+137 using the full form Plus[42, 137] */
MLPutFunction(link, "Plus", 2);
MLPutInteger(link, 42);
MLPutInteger(link, 137);
MLEndPacket(link);
/* get packets until we find a ReturnPacket or error */
while ((packet = MLNextPacket(link)) && packet != RETURNPKT)
MLNewPacket(link);
if (MLError(link))
printf("error.\n");
else {
int result;
MLGetInteger(link, &result); /* we know that the result is an integer in this case */
printf("result: %d\n", result);
}
return 0;
}
Instructions for compiling MathLink programs are found here, separately for all three major platforms. I used the following makefile on OS X:
MLINKDIR = /Applications/Mathematica\ 9.app/SystemFiles/Links/MathLink/DeveloperKit
SYS=MacOSX-x86-64
CADDSDIR = ${MLINKDIR}/${SYS}/CompilerAdditions
INCDIR = ${CADDSDIR}
LIBDIR = ${CADDSDIR}
EXTRA_OPT = -framework Foundation -lstdc++
mlcall: mlcall.c
$(CC) -O mlcall.c -I$(INCDIR) -L$(LIBDIR) $(EXTRA_OPT) -lMLi3 -o mlcall
The EXTRA_OPT
part is going to be different on Linux. Also, pay attention to the correct formatting of the makefile, as tabs are not preserved here, and the LIBDIR line shouldn't be indented (an SE bug causes it to be).
I was running it using the following command. Since we're passing the command line arguments of our program directly to MLOpenArgcArgv
, we can use the usual MathLink options. -linkmode launch
means that the executable matching the -linkname
will be launched and a MathLink connection opened to it.
./mlcall -linkmode launch -linkname "/Applications/Mathematica\ 9.app/Contents/MacOS/MathKernel"
You can also use create
or connect
link modes, which correspond to LinkCreate
and LinkConnect
.
At first, some of the functions used here may seem a bit scary. To understand what is happening, first you need to understand Mathematica expressions (you're probably familiar with this already). Then I'd recommend to look at how to call C functions from Mathematica using MathLink. Learn how to use template files first. Then learn how to pass arguments and retrieve return values manually. Looking at the source code that mprep
generates from the template file will be useful here. After you have tackled these tasks, it will be much easier to understand how calling Mathematica from C works.