Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

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

I am attempting to use Mathlink from C. I have managed to return single values from mathlink to my c program, but I am having trouble with lists.

Consider the Mathematica operation:

NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}]

This gives us:

{{x -> -0.438447, y -> 1.56155}, {x -> -4.56155, y -> -2.56155}}

Say I wanted to return to my C program a list containing only the second solution i.e. I want {-4.56155,-2.56155}}.

I could do this

 List[NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[1]][[2]], 
 NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[2]][[2]]]

In mathematica, this gives me:

{-4.56155, -2.56155}

All very well, but I worried mathematica is doing Nsolve twice.

When I try to replicate this through C like this:

MLPutFunction(link, "EvaluatePacket", 1);
    MLPutFunction(link, "ToExpression", 1);
    MLPutString(link, (const char *)"List[NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[2]][[2]], NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[1]][[2]]]");

    while (MLNextPacket(link) != RETURNPKT)

    double *list;
    long length;

    MLGetRealList(link, &list, &length);


    MLDisownRealList(link, list, length);

EDIT: The program sort of completes, but I thin kit is crashing at the end.

Now when I print out list[0] and list[1] I get the right answer followed by a hex value.



1) How can I return a list of numbers in an elegant fashion through Mathlink? 2) Why is it crashing?


share|improve this question

Your Answer


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

Browse other questions tagged or ask your own question.