When you install a Wolfram Symbolic Transfer Protocol (WSTP)‐compatible external program using Install, the program is set up to behave somewhat like a simplified Wolfram Language kernel. Every time you call a function in the external program, a CallPacket is sent to the program, and the program responds by sending back a result wrapped in a ReturnPacket.
If you use Install several times on a single external program, the Wolfram System will open several WSTP connections to the program. Each connection will however always correspond to a unique LinkObject.
|$CurrentLink||the WSTP connection to the external program currently being run|
:Pattern: addto[$CurrentLink, n_Integer]
int counter = 0;
int addto(int n)
counter += n;
If an external program maintains information about its state then you can use different instances of the program to represent different states. $CurrentLink then provides a way to refer to each instance of the program.
The value of $CurrentLink is temporarily set every time a particular instance of the program is called, as well as when each instance of the program is first installed.
|WSEvaluateString(stdlink,"string")||send input to the Wolfram System but return no results|
In the simplest case, you can use the WSTP function to send a string to the Wolfram System. The Wolfram System will evaluate this string, producing whatever effects the string specifies, but it will not return any results from the evaluation back to the external program.
WSPutFunction(stdlink, "EvaluatePacket", 1);
WSPutFunction(stdlink, "Factorial", 1);
WSCheckFunction(stdlink, "ReturnPacket", &n);
|WSEndPacket(stdlink)||specify that a packet is finished and ready to be sent to the Wolfram System|
When you can send the Wolfram System an EvaluatePacket[input], it may in general produce many packets in response, but the final packet should be ReturnPacket[output]. "Manipulating Expressions in External Programs" discusses how to handle sequences of packets and expressions whose structure you do not know in advance.