How to purge contents of Mathlink buffer after errors sent.
- To: mathgroup at smc.vnet.net
- Subject: [mg93635] How to purge contents of Mathlink buffer after errors sent.
- From: thekiwi <a.o.koetsier at uu.nl>
- Date: Wed, 19 Nov 2008 05:39:43 -0500 (EST)
I'm using the Mathlink C API with GSL to perform some root finding, send the results back to Mathematica using MLPutRealList() and make plots of the roots in real time. For certain parameter values my equations are singular and the root finder fails. No problem, I have an error handler which calls a routine to send an error message to Mathematica. This routine is: void dispatchMLinkError(char *err_msg_link) { MLClearError(stdlink); MLNewPacket(stdlink); MLPutSymbol(stdlink,"$Failed"); MLEndPacket(stdlink); MLEvaluateString(stdlink,"Message[GSL::err,"singular"]); MLFlush(stdlink); } If I evaluate my function for singular parameters I get the value $Failed and a message telling me as much, I can do this several times (when plotting, often there are several such singular calls which return an error). The problem is, after I get errors (which work as expected), subsequent calls to my root finder using known non-singular parameters return junk. They returned consistent, sensible values before the error. I eventually figured that the error places a number of items on the link (a mixture of numbers, error messages and $Failed values) that had to be cleared. This I can achieve using While[LinkReadyQ[link], LinkRead[link]]//Quiet; which reads the link until there's nothing left to be read. Thereafter everything is back to normal. My question is, how can I discard junk waiting to be read on the link in this manner from the C code? I tried calling MLNewPacket(stdlink); several times but this doesn't seem to purge the link. I'd like to do this so that whenever there's an error, the link gets cleared automatically by the error handler without me having to purge it manually in Mathematica using the above commands. This is especially annoying when calling the external function within a Plot[] or Manipulate[] block, for example.