This is a simple C++ program to send an expression to the_Mathematica_ Kernel and get its response.
#include <mathlink.h> //mathlink header
#include <stdio.h> //standard io header
#include <stdlib.h>
#include <iostream>
using namespace std;
/* initialising variables */
MLENV env = (MLENV)0;
MLINK link = (MLINK)0;
int MLEvaluate(MLINK mlp, char* s)
{
return MLPutFunction(mlp, "EvaluatePacket", 1L)
&& MLPutFunction(mlp, "ToExpression", 1L)
&& MLPutString(mlp, s)
&& MLEndPacket(mlp);
} /* MLEvaluate */
int main(int argc, char *argv[]) {
int errno;
int packet;
char input[255];
/* initialises MathLink environemnt object */
env = MLInitialize(0);
/* links the program to the MathKernel */
link = MLOpenString(env, "-linkmode launch -linkname 'C:\\Program Files\\Wolfram Research\\Mathematica\\9.0\\math.exe'", &errno);
MLActivate(link); //activates a MathLink connection with a mathlink program
cout << "Enter your expression: ";
cin >> input;
MLEvaluate(link, input);
/* get packets until we find a ReturnPacket or error */
while ((packet = MLNextPacket(link)) && packet != RETURNPKT) MLNewPacket(link);
/* once the results is returned */
if (MLError(link)) printf("\nError Has Occured!\n"); //if an error is returned
else { //if an integer is returned
int result;
const char *string;
MLGetString(link, &string);
printf("\nResult: %s\n", string);
MLReleaseString(link, string);
}
printf("\nPress Enter to Exit...");
getchar(); //holds the console till users presses enter
getchar(); //holds the console till users presses enter
return 0;
}
When I type the expression show below in response to the console prompt
2+2
I get an answer. However, when I type in
2+a
I dont seem to be able to read the answer as string
Where did I go wrong? Please advise