Here is an implementation based on Simon's code. It still requires improvement. The one unclear thing to me is how to handle Messages generated in the slave (v.5.2) kernel.
Here is my code:
Clear[linkEvaluate]
SetAttributes[linkEvaluate, HoldRest]
linkEvaluate[link_LinkObject, expr_] := Catch[
Module[{out = {}, postScript = {}, packet, outputs = {}},
While[LinkReadyQ[link],
Print["From the buffer:", LinkRead[link]]];
LinkWrite[link, Unevaluated[EnterExpressionPacket[expr]]];
While[Not@MatchQ[packet = LinkRead[link], InputNamePacket[_]],
Switch[packet,
DisplayPacket[_], AppendTo[postScript, First@packet],
DisplayEndPacket[_], AppendTo[postScript, First@packet];
CellPrint@
Cell[GraphicsData["PostScript", #], "Output",
CellLabel -> "Kernel 5.2 PostScript ="] &@
StringJoin[postScript]; postScript = {},
TextPacket[_],
If[StringMatchQ[First@packet,
WordCharacter .. ~~ "::" ~~ WordCharacter .. ~~ ": " ~~ __],
CellPrint@
Cell[BoxData@
RowBox[{StyleBox["Kernel 5.2 Message = ",
FontColor -> Blue], First@packet}], "Message"],
CellPrint@
Cell[First@packet, "Output", CellLabel -> "Kernel 5.2 Print"]],
OutputNamePacket[_], AppendTo[outputs, First@packet];,
ReturnExpressionPacket[_], AppendTo[outputs, First@packet];,
_, AppendTo[out, packet]
]
];
If[Length[out] > 0, Print[out]];
Which[
(l = Length[outputs]) == 0, Null,
l == 2, Last@outputs,
True, multipleOutput[outputs]
]
]];
Clear[kernel5Evaluate]
SetAttributes[kernel5Evaluate, HoldAll]
kernel5Evaluate[expr_] :=
If[TrueQ[MemberQ[Links[], $kern5]], linkEvaluate[$kern5, expr],
Clear[$kern5]; $kern5 = LinkLaunch[
"C:\Program Files\Wolfram Research\Mathematica\5.2\MathKernel.exe -mathlink"];
LinkRead[$kern5];
LinkWrite[$kern5,
Unevaluated[EnterExpressionPacket[$MessagePrePrint = InputForm;]]];
LinkRead[$kern5]; kernel5Evaluate[expr]]
Here are test expressions:
plot = kernel5Evaluate[Plot3D[Sin[x y], {x, 0, Pi}, {y, 0, Pi}]]
plot = kernel5Evaluate[Plot[Sin[x], {x, 0, Pi}]; Plot[Sin[x], {x, -Pi, Pi}]] //
DeleteCases[#, HoldPattern[DefaultFont :> $DefaultFont], Infinity] &
s = kernel5Evaluate[
NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}]]
s // InputForm // Short
kernel5Evaluate[1/0; Print["s"];]
It seems to work as expected. However it could be better...