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?



1 Answer 1


this problem can be fixed by changing




Your Answer

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

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