1
$\begingroup$

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

$\endgroup$
2
  • 2
    $\begingroup$ You should (nearly) always check what the return type is (string, symbol, etc.). Add that to your code, see what it tells you. $\endgroup$
    – ciao
    Mar 7, 2014 at 4:38
  • $\begingroup$ 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 $\endgroup$ Mar 7, 2014 at 5:43

1 Answer 1

2
$\begingroup$

Yes: Just use

return MLPutFunction(mlp, "EvaluatePacket", 1L)
    && MLPutFunction(mlp, "ToString", 1L)       // <<<--- !
    && MLPutFunction(mlp, "ToExpression", 1L)
    /* ... */
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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