1
$\begingroup$

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]]]");
    MLEndPacket(link);

    while (MLNextPacket(link) != RETURNPKT)
    {
         MLNewPacket(link);
    }

    double *list;
    long length;

    MLGetRealList(link, &list, &length);

    std::cout<<list[0]<<std::cout;

    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.

E.g.:

-4.561550x7fff7986fb68

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

Thanks

$\endgroup$
2
$\begingroup$

this problem can be fixed by changing

std::cout<<list[0]<<std::cout;

to

std::cout<<list[0]<<std::endl;
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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