Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


I get an answer. However, when I type in


I dont seem to be able to read the answer as string

Where did I go wrong? Please advise

share|improve this question
You should (nearly) always check what the return type is (string, symbol, etc.). Add that to your code, see what it tells you. – ciao Mar 7 '14 at 4:38
It returns 2+a as a function(MLTKFUNC) Plus. Is there another way to get the entire output instead? For example, just 2+a as a string – arvindrajan92 Mar 7 '14 at 5:43

Yes: Just use

return MLPutFunction(mlp, "EvaluatePacket", 1L)
    && MLPutFunction(mlp, "ToString", 1L)       // <<<--- !
    && MLPutFunction(mlp, "ToExpression", 1L)
    /* ... */
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.