public interface KernelLink extends MathLink
Objects of type KernelLink are created by the createKernelLink() method in the MathLinkFactory class.
MathLink
,
MathLinkFactory
Modifier and Type | Field and Description |
---|---|
static int |
MLE_BAD_OBJECT
Error code in a MathLinkException when getObject() was called and a valid Java
object was not on the link.
|
static int |
MLTKOBJECT
Returned by the KernelLink methods getNext() and getType() to represent that
a Java object is waiting to be read from the link.
|
static java.lang.String |
PACKAGE_CONTEXT
The Mathematica package context for the J/Link support functions.
|
static int |
TYPE_OBJECT
This is an extension to the TYPE_xxx constants in the MathLink interface used in getArray().
|
static java.lang.String |
VERSION
The version string identifying this release.
|
static double |
VERSION_NUMBER
The major version number identifying this release.
|
BEGINDLGPKT, CALLPKT, DISPLAYENDPKT, DISPLAYPKT, ENDDLGPKT, ENTEREXPRPKT, ENTERTEXTPKT, EVALUATEPKT, EXPRESSIONPKT, FEPKT, FIRSTUSERPKT, ILLEGALPKT, INPUTNAMEPKT, INPUTPKT, INPUTSTRPKT, LASTUSERPKT, MENUPKT, MESSAGEPKT, MLABORTMESSAGE, MLAUTHENTICATEFAILURE, MLE_ARRAY_TOO_SHALLOW, MLE_BAD_COMPLEX, MLE_CONNECT_TIMEOUT, MLE_CREATION_FAILED, MLE_FIRST_USER_EXCEPTION, MLE_LINK_IS_NULL, MLE_NON_ML_ERROR, MLE_OUT_OF_MEMORY, MLE_WRAPPED_EXCEPTION, MLEOK, MLEUSER, MLINTERRUPTMESSAGE, MLTERMINATEMESSAGE, MLTKERR, MLTKFUNC, MLTKINT, MLTKREAL, MLTKSTR, MLTKSYM, OUTPUTNAMEPKT, RESUMEPKT, RETURNEXPRPKT, RETURNPKT, RETURNTEXTPKT, SUSPENDPKT, SYNTAXPKT, TEXTPKT, TYPE_BIGDECIMAL, TYPE_BIGINTEGER, TYPE_BOOLEAN, TYPE_BYTE, TYPE_CHAR, TYPE_COMPLEX, TYPE_DOUBLE, TYPE_EXPR, TYPE_FLOAT, TYPE_INT, TYPE_LONG, TYPE_SHORT, TYPE_STRING
Modifier and Type | Method and Description |
---|---|
void |
abandonEvaluation()
Causes any method that is blocking waiting for output from the kernel to return immediately
and throw a MathLinkException.
|
void |
abortEvaluation()
Sends a request to the kernel to abort the current evaluation.
|
void |
addPacketListener(PacketListener listener)
Adds the specified PacketListener to receive PacketArrivedEvents.
|
void |
beginManual()
Informs J/Link that your code will be manually sending the result back to Mathematica.
|
void |
clearInterrupt()
Call this method after you have handled an interrupt request manually.
|
void |
discardAnswer()
Reads and discards all packets generated during a computation.
|
void |
enableObjectReferences()
Call this method to enable the ability to pass Java objects "by reference"
to Mathematica.
|
Expr |
enableObjectReferences(boolean becomeDefaultJVM)
Call this method to enable the ability to pass Java objects "by reference"
to Mathematica.
|
void |
evaluate(Expr e)
Sends an Expr for evaluation.
|
void |
evaluate(java.lang.String s)
Sends a string for evaluation.
|
byte[] |
evaluateToImage(Expr e,
int width,
int height)
Sends graphics or plotting code to evaluate, then reads and discards all output
except for the image data, which is returned as a byte array of GIF data.
|
byte[] |
evaluateToImage(Expr e,
int width,
int height,
int dpi,
boolean useFE)
Sends graphics or plotting code to evaluate, then reads and discards all output
except for the image data, which is returned as a byte array of GIF data.
|
byte[] |
evaluateToImage(java.lang.String s,
int width,
int height)
Sends graphics or plotting code to evaluate, then reads and discards all output
except for the image data, which is returned as a byte array of GIF data.
|
byte[] |
evaluateToImage(java.lang.String s,
int width,
int height,
int dpi,
boolean useFE)
Sends graphics or plotting code to evaluate, then reads and discards all output
except for the image data, which is returned as a byte array of GIF data.
|
java.lang.String |
evaluateToInputForm(Expr e,
int pageWidth)
Sends an Expr to evaluate, then reads and discards all output except for the
result, which is returned.
|
java.lang.String |
evaluateToInputForm(java.lang.String s,
int pageWidth)
Sends a string to evaluate, then reads and discards all output except for the
result, which is returned.
|
java.lang.String |
evaluateToOutputForm(Expr e,
int pageWidth)
Sends an Expr to evaluate, then reads and discards all output except for the
result, which is returned.
|
java.lang.String |
evaluateToOutputForm(java.lang.String s,
int pageWidth)
Sends a string to evaluate, then reads and discards all output except for the
result, which is returned.
|
byte[] |
evaluateToTypeset(Expr e,
int width,
boolean useStdForm)
Sends an Expr to evaluate, the result of which will be typeset, converted to a GIF,
and the resulting data returned.
|
byte[] |
evaluateToTypeset(java.lang.String s,
int width,
boolean useStdForm)
Sends a string to evaluate, the result of which will be typeset, converted to a GIF,
and the resulting data returned.
|
java.lang.Object |
getArray(java.lang.Class elementType,
int depth)
An improvement on the KernelLink.getArray(int type, int depth) signature that allows you to specify
the type of array to create when reading arrays of Java objects.
|
java.lang.Object |
getArray(java.lang.Class elementType,
int depth,
java.lang.String[] heads)
An improvement on the KernelLink.getArray(int type, int depth, String[] heads) signature that allows you to specify
the type of array to create when reading arrays of Java objects.
|
java.lang.Object |
getArray(int type,
int depth)
Extends the MathLink method of the same signature by allowing the extra type specification TYPE_OBJECT.
|
java.lang.Object |
getArray(int type,
int depth,
java.lang.String[] heads)
Extends the MathLink method of the same signature by allowing the extra type specification TYPE_OBJECT.
|
JLinkClassLoader |
getClassLoader()
Gets the JLinkClassLoader that is used by this link to load classes via the
LoadJavaClass[] Mathematica function.
|
java.lang.Throwable |
getLastError()
Returns the Throwable object that represents any exception detected during the last call
of one of the "evaluateTo" methods (evaluateToInputForm(), evaluateToOutputForm(),
evaluateToImage(), evaluateToTypeset()).
|
int |
getNext()
Extends the MathLink method of the same name by allowing the extra return type MLTKOBJECT.
|
java.lang.Object |
getObject()
Reads a Java object reference from the link.
|
int |
getType()
Extends the MathLink method of the same name by allowing the extra return type MLTKOBJECT.
|
void |
handlePacket(int pkt)
Call this to invoke J/Link's internal handling of special packet types.
|
void |
interruptEvaluation()
Sends a request to the kernel to interrupt the current evaluation.
|
void |
message(java.lang.String symtag,
java.lang.String arg)
Prints the specified message in the user's Mathematica session.
|
void |
message(java.lang.String symtag,
java.lang.String[] args)
Prints the specified message in the user's Mathematica session.
|
boolean |
notifyPacketListeners(int pkt)
Call this method to invoke the normal notification of registered PacketListeners
if you are manually reading packets with nextPacket().
|
void |
print(java.lang.String s)
Prints the specified text in the user's Mathematica session.
|
void |
put(java.lang.Object obj)
Sends an object.
|
void |
putReference(java.lang.Object obj)
Sends an object to Mathematica "by reference".
|
void |
removePacketListener(PacketListener listener)
Removes the specified PacketListener object so that it no longer receives
PacketArrivedEvents.
|
void |
setClassLoader(JLinkClassLoader loader)
Sets the JLinkClassLoader that is used by this link to load classes via the
LoadJavaClass[] Mathematica function.
|
void |
terminateKernel()
Sends a request to the kernel to shut down.
|
int |
waitForAnswer()
Reads and discards all packets that arrive up until the packet that contains the
result of the computation.
|
boolean |
wasInterrupted()
Tells whether the user has attempted to abort the computation.
|
activate, addMessageHandler, bytesToGet, bytesToPut, checkFunction, checkFunctionWithArgCount, clearError, close, connect, connect, createMark, destroyMark, endPacket, error, errorMessage, flush, getArgCount, getBoolean, getBooleanArray1, getBooleanArray2, getByteArray1, getByteArray2, getByteString, getCharArray1, getCharArray2, getComplex, getComplexArray1, getComplexArray2, getComplexClass, getData, getDouble, getDoubleArray1, getDoubleArray2, getExpr, getFloatArray1, getFloatArray2, getFunction, getIntArray1, getIntArray2, getInteger, getLongArray1, getLongArray2, getLongInteger, getMessage, getShortArray1, getShortArray2, getString, getStringArray1, getStringArray2, getSymbol, messageReady, name, newPacket, nextPacket, peekExpr, put, put, put, put, put, putArgCount, putByteString, putData, putData, putFunction, putMessage, putNext, putSize, putSymbol, ready, removeMessageHandler, seekMark, setComplexClass, setError, setYieldFunction, transferExpression, transferToEndOfLoopbackLink
static final java.lang.String VERSION
static final double VERSION_NUMBER
static final java.lang.String PACKAGE_CONTEXT
BAD: ml.evaluate("Needs[\"JLink`\"]"); GOOD: ml.evaluate("Needs[\" + KernelLink.PACKAGE_CONTEXT + \"]");
static final int MLTKOBJECT
static final int TYPE_OBJECT
static final int MLE_BAD_OBJECT
void evaluate(java.lang.String s) throws MathLinkException
This method only sends the computation--it does not read any resulting packets off the link. You would typically follow a call to evaluate() with either waitForAnswer() or discardAnswer(), which read data from the link.
s
- the string of Mathematica codeMathLinkException
waitForAnswer()
,
discardAnswer()
void evaluate(Expr e) throws MathLinkException
This method only sends the computation--it does not read any resulting packets off the link. You would typically follow a call to evaluate() with either waitForAnswer() or discardAnswer(), which read data from the link.
e
- the Expr to evaluateMathLinkException
java.lang.String evaluateToInputForm(java.lang.String s, int pageWidth)
s
- the string to evaluatepageWidth
- the page width, in characters, to format the outputjava.lang.String evaluateToInputForm(Expr e, int pageWidth)
e
- the Expr to evaluatepageWidth
- the page width, in characters, to format the output. Pass 0 for InfinitygetLastError()
java.lang.String evaluateToOutputForm(java.lang.String s, int pageWidth)
s
- the string to evaluatepageWidth
- the page width, in characters, to format the output. Pass 0 for InfinitygetLastError()
java.lang.String evaluateToOutputForm(Expr e, int pageWidth)
e
- the Expr to evaluatepageWidth
- the page width, in characters, to format the output. Pass 0 for InfinitygetLastError()
byte[] evaluateToImage(java.lang.String s, int width, int height)
width
X
height
, without changing its aspect ratio. In other words, the image
might not have exactly these dimensions, but it will never be larger.
To get image data returned in JPEG format instead of GIF, set the Mathematica symbol JLink`$DefaultImageFormat = "JPEG".
If s does not evaluate to a graphics expression, then null is returned. It is not enough that the computation causes a plot to be generated--the return value of the computation must be a Mathematica Graphics (or Graphics3D, SurfaceGraphics, etc.) expression. For example:
BAD: ml.evaluateToImage("Plot[x,{x,0,1}]; 42"); GOOD: ml.evaluateToImage("Plot[x,{x,0,1}]");To create an Image from the data, you can do the following:
byte[] gifData = ml.evaluateToImage(someInput, 0, 0); java.awt.Image im = java.awt.Toolkit.getDefaultToolkit().createImage(gifData);
s
- the string to evaluatewidth
- the image width, in pixels. Pass 0 for Automatic, or if the expression itself
specifies the widthheight
- the image height, in pixels. Pass 0 for Automatic, or if the expression itself
specifies the heightgetLastError()
byte[] evaluateToImage(Expr e, int width, int height)
width
X
height
, without changing its aspect ratio. In other words, the image
might not have exactly these dimensions, but it will never be larger.
To get image data returned in JPEG format instead of GIF, set the Mathematica symbol JLink`$DefaultImageFormat = "JPEG".
If e does not evaluate to a graphics expression, then null is returned. It is not enough that the computation causes a plot to be generated--the return value of the computation must be a Mathematica Graphics (or Graphics3D, SurfaceGraphics, etc.) expression.
To create an Image from the data, you can do the following:
byte[] gifData = ml.evaluateToImage(someInput, 0, 0); java.awt.Image im = java.awt.Toolkit.getDefaultToolkit().createImage(gifData);
e
- the Expr to evaluatewidth
- the image width, in pixels. Pass 0 for Automatic, or if the expression itself
specifies the widthheight
- the image height, in pixels. Pass 0 for Automatic, or if the expression itself
specifies the heightgetLastError()
byte[] evaluateToImage(java.lang.String s, int width, int height, int dpi, boolean useFE)
width
X
height
, without changing its aspect ratio. In other words, the image
might not have exactly these dimensions, but it will never be larger. The image
resolution, in dots per inch, is specified by dpi
. The useFE
parameter controls whether the notebook front end will be used for rendering
services. If it is used, the front end will be run on the same machine as the kernel.
To get image data returned in JPEG format instead of GIF, set the Mathematica symbol JLink`$DefaultImageFormat = "JPEG".
If s does not evaluate to a graphics expression, then null is returned. It is not enough that the computation causes a plot to be generated--the return value of the computation must be a Mathematica Graphics (or Graphics3D, SurfaceGraphics, etc.) expression. For example:
BAD: ml.evaluateToImage("Plot[x,{x,0,1}]; 42"); GOOD: ml.evaluateToImage("Plot[x,{x,0,1}]");To create an Image from the data, you can do the following:
byte[] gifData = ml.evaluateToImage(someInput, 0, 0, 0, false); java.awt.Image im = java.awt.Toolkit.getDefaultToolkit().createImage(gifData);
s
- the string to evaluatewidth
- the image width, in pixels. Pass 0 for Automatic, or if the expression itself
specifies the widthheight
- the image height, in pixels. Pass 0 for Automatic, or if the expression itself
specifies the heightdpi
- the resolution, in dots (pixels) per inch. Pass 0 for Automatic, or if the expression itself
specifies the resolutionuseFE
- whether to use the notebook front end for rendering servicesgetLastError()
byte[] evaluateToImage(Expr e, int width, int height, int dpi, boolean useFE)
width
X
height
, without changing its aspect ratio. In other words, the image
might not have exactly these dimensions, but it will never be larger. The image
resolution, in dots per inch, is specified by dpi
. The useFE
parameter controls whether the notebook front end will be used for rendering
services. If it is used, the front end will be run on the same machine as the kernel.
To get image data returned in JPEG format instead of GIF, set the Mathematica symbol JLink`$DefaultImageFormat = "JPEG".
If s does not evaluate to a graphics expression, then null is returned. It is not enough that the computation causes a plot to be generated--the return value of the computation must be a Mathematica Graphics (or Graphics3D, SurfaceGraphics, etc.) expression.
To create an Image from the data, you can do the following:
byte[] gifData = ml.evaluateToImage(someInput, 0, 0, 0, false); java.awt.Image im = java.awt.Toolkit.getDefaultToolkit().createImage(gifData);
e
- the Expr to evaluatewidth
- the image width, in pixels. Pass 0 for Automatic, or if the expression itself
specifies the widthheight
- the image height, in pixels. Pass 0 for Automatic, or if the expression itself
specifies the heightdpi
- the resolution, in dots (pixels) per inch. Pass 0 for Automatic, or if the expression itself
specifies the resolutionuseFE
- whether to use the notebook front end for rendering servicesgetLastError()
byte[] evaluateToTypeset(java.lang.String s, int width, boolean useStdForm)
useStdForm
is true, and TraditionalForm otherwise.
The result will be wrapped to width
pixels during typesetting.
The notebook front end will be used for rendering services; it will be run on the
same machine as the kernel.
To create an Image from the data, you can do the following:
byte[] gifData = ml.evaluateToTypeset(someInput, 0, true); java.awt.Image im = java.awt.Toolkit.getDefaultToolkit().createImage(gifData);
s
- the string to evaluatewidth
- the width to wrap the output to during typesetting, in pixels
(a rough measure). Pass 0 for InfinityuseStdForm
- true for StandardForm, false for TraditionalFormgetLastError()
byte[] evaluateToTypeset(Expr e, int width, boolean useStdForm)
useStdForm
is true, and TraditionalForm otherwise.
The result will be wrapped to width
pixels during typesetting.
The notebook front end will be used for rendering services; it will be run on the
same machine as the kernel.
To create an Image from the data, you can do the following:
byte[] gifData = ml.evaluateToTypeset(someInput, 0, true); java.awt.Image im = java.awt.Toolkit.getDefaultToolkit().createImage(gifData);
e
- the Expr to evaluatewidth
- the width to wrap the output to during typesetting, in pixels
(a rough measure). Pass 0 for InfinityuseStdForm
- true for StandardForm, false for TraditionalFormgetLastError()
java.lang.Throwable getLastError()
int waitForAnswer() throws MathLinkException
Use this after sending an expression to evaluate with evaluate()
or a manual
sequence of put methods.
ml.evaluate("2+2"); ml.waitForAnwser(); int result = ml.getInteger(); // It is not strictly necessary to call newPacket, since we have read the entire // packet contents, but it is good style. ml.newPacket();If you are not interested in examining the result of the evaluation, use discardAnswer() instead.
Examples of packets that arrive before the result and are discarded are TEXTPKT, MESSAGEPKT, DISPLAYPKT, etc. If you want to examine or operate on the incoming packets that are discarded by this method, use the PacketListener interface.
It returns the packet type that held the result of the computation. Typically, this will be RETURNPKT. However, if you are manually sending evaluations inside an EnterTextPacket or EnterExpressionPacket, there are some further issues that you need to understand; consult the J/Link User Guide for details.
MathLinkException
discardAnswer()
,
evaluate(String)
,
evaluate(Expr)
void discardAnswer() throws MathLinkException
Use this after sending an expression to evaluate with evaluate()
or a manual
sequence of put methods.
If you are interested in examining the result of the evaluation, use waitForAnswer() instead.
If you want to examine or operate on the incoming packets that are discarded by this method, use the PacketListener interface.
MathLinkException
waitForAnswer()
,
evaluate(String)
,
evaluate(Expr)
void handlePacket(int pkt) throws MathLinkException
If you absolutely must write your own packet loop instead of using the PacketListener interface (this is strongly discouraged), you should call this method if a call to nextPacket() returns a packet type that you are not handling entirely with your own code. In fact, you can call handlePacket() for every packet you read with nextPacket(). For example, here is a basic packet loop:
boolean done = false; while (!done) { int pkt = ml.nextPacket(); if (ml.notifyPacketListeners(pkt)) ml.handlePacket(pkt); switch (pkt) { case MathLink.RETURNPKT: // read and handle contents of ReturnPacket ... done = true; break; case MathLink.TEXTPKT: // read and handle contents of TextPacket ... break; .. etc for other packet types } ml.newPacket(); }To remind again, writing your own packet loop like this is strongly discouraged. Use waitForAnswer(), discardAnswer(), or one of the "evaluateTo" methods instead. These methods hide the packet loop within them. If you want more information about what packet types arrive and their contents, simply use the PacketListener interface.
An example of the special type of packets that your packet loop might encounter is CALLPKT. Encountering a CALLPKT means that Mathematica code is trying to call into Java using the mechanism described in Part 1 of the J/Link User Guide. Only the internals of J/Link know how to manage these callbacks, so the handlePacket() method provides a means to invoke this handling for you.
If you are using waitForAnswer(), discardAnswer(), or any of the "evaluateTo" methods, and therefore not writing your own packet loop, you do not need to be concerned with handlePacket().
After handlePacket() returns you should call newPacket().
MathLinkException
waitForAnswer()
void put(java.lang.Object obj) throws MathLinkException
Behaves like the put(Object) method in the MathLink interface for objects that have a meaningful "value" representation in Mathematica. This set is:
null: sent as the symbol Null. strings: sent as Mathematica strings arrays: sent as lists of the appropriate dimensions Expr: sent as expressions Wrapper classes (e.g., Boolean, Integer, Float, etc.): sent as their values BigDecimal and BigInteger: sent as their values complex numbers: sent as ComplexFor other objects, behaves like putReference(). In other words, the KernelLink interface changes the semantics of put(Object) compared to the MathLink interface by adding the ability to send object references to Mathematica for objects whose values are not meaningful. You must call enableObjectReferences() before calling put(Object) on an object that will be sent by reference. See notes for putReference().
put
in interface MathLink
obj
- the object to sendMathLinkException
putReference(Object)
,
enableObjectReferences()
void putReference(java.lang.Object obj) throws MathLinkException
Use this method to pass Java objects to Mathematica so that methods can be invoked directly from Mathematica code as described in Part 1 of the J/Link User Guide.
The put() method will also put some objects by reference, but there are two reasons to call putReference() instead:
(1) You want to force an object that would normally be sent by value (for example, a string) to be sent by reference. (2) You know that the object is a type that put() will send by reference. By calling putReference() directly, you can save the effort put() would expend figuring this out.
obj
- the object to sendMathLinkException
put(Object)
,
enableObjectReferences()
,
getObject()
java.lang.Object getObject() throws MathLinkException
Once you have called enableObjectReferences(), you can pass object references to Mathematica via putReference() and read them from Mathematica via getObject().
MathLinkException
putReference(Object)
,
enableObjectReferences()
int getNext() throws MathLinkException
getNext
in interface MathLink
MathLinkException
MathLink.getNext()
,
enableObjectReferences()
int getType() throws MathLinkException
getType
in interface MathLink
MathLinkException
MathLink.getType()
,
enableObjectReferences()
java.lang.Object getArray(int type, int depth) throws MathLinkException
getArray
in interface MathLink
type
- The desired type for the returned array. Must be one of TYPE_BOOLEAN, TYPE_BYTE,
TYPE_CHAR, TYPE_SHORT, TYPE_INT, TYPE_LONG, TYPE_FLOAT, TYPE_DOUBLE, TYPE_STRING,
TYPE_BIGINTEGER, TYPE_BIGDECIMAL, TYPE_EXPR, or TYPE_COMPLEX.depth
- the depth of the returned arrayMathLinkException
- if the incoming expression is not an array of the requested type
or is not as deep as requestedMathLink.getArray(int, int)
,
enableObjectReferences()
java.lang.Object getArray(int type, int depth, java.lang.String[] heads) throws MathLinkException
getArray
in interface MathLink
type
- The desired type for the returned array. Must be one of TYPE_BOOLEAN, TYPE_BYTE,
TYPE_CHAR, TYPE_SHORT, TYPE_INT, TYPE_LONG, TYPE_FLOAT, TYPE_DOUBLE, TYPE_STRING,
TYPE_BIGINTEGER, TYPE_BIGDECIMAL, TYPE_EXPR, or TYPE_COMPLEX.depth
- the depth of the returned arrayheads
- an array of length 'depth' that will be filled with the heads at each levelMathLinkException
- if the incoming expression is not an array of the requested type,
or is not as deep as requestedMathLink.getArray(int, int, String[])
,
enableObjectReferences()
java.lang.Object getArray(java.lang.Class elementType, int depth) throws MathLinkException
Object[] a = (Object[]) ml.getArray(Object.class, 1);
MathLinkException
MathLink.getArray(int, int)
,
getArray(Class, int, String[])
,
enableObjectReferences()
java.lang.Object getArray(java.lang.Class elementType, int depth, java.lang.String[] heads) throws MathLinkException
MathLinkException
MathLink.getArray(int, int, String[])
,
getArray(Class, int)
,
enableObjectReferences()
void enableObjectReferences() throws MathLinkException
This method requires that the JLink.m file be present in the JLink directory (its default location if J/Link is properly installed).
MathLinkException
enableObjectReferences(boolean)
,
putReference(Object)
Expr enableObjectReferences(boolean becomeDefaultJVM) throws MathLinkException
The method returns the JVM expression that you can use in UseJVM or other constructs to identify this Java runtime as the target for calls from Java into Mathematica.
You must call this before attempting to call putReference(), or put() on an object that will be put by reference.
This method requires that the JLink.m file be present in the JLink directory (its default location if J/Link is properly installed).
MathLinkException
enableObjectReferences()
,
putReference(Object)
void addPacketListener(PacketListener listener)
Use this method to register a PacketListener object to receive notifications when packets are read by any of the KernelLink methods that run internal packet loops. These methods are: waitForAnswer(), discardAnswer(), evaluateToInputForm(), evaluateToOutputForm(), evaluateToImage(), and evaluateToTypeset().
J/Link programmers are discouraged from writing their own packet loops (i.e., repeatedly calling nextPacket() and newPacket() until a desired packet arrives). Instead, they should create a class that implements PacketListener, register an object of this class using addPacketListener(), and then use the KernelLink methods that manage the packet loop for you.
listener
- the PacketListener to registerremovePacketListener(PacketListener)
,
PacketArrivedEvent
,
PacketPrinter
void removePacketListener(PacketListener listener)
listener
- the PacketListener to removeaddPacketListener(PacketListener)
,
PacketArrivedEvent
,
PacketPrinter
boolean notifyPacketListeners(int pkt)
The KernelLink methods that run internal packet loops (waitForAnswer(), discardAnswer(), evaluateToInputForm(), evaluateToOutputForm(), evaluateToImage(), and evaluateToTypeset()) call this method for each packet to trigger the notification of registered PacketListeners. If you are reading packets yourself by calling nextPacket() (this is discouraged), you can call notifyPacketListeners() to cause PacketListeners to be notified for these packets as well. Call it right after nextPacket(), passing it the packet type as returned by nextPacket(). The state of the link (the current position in the incoming data stream) will be unaffected by the call.
pkt
- the packet type (as returned by nextPacket())removePacketListener(PacketListener)
,
addPacketListener(PacketListener)
JLinkClassLoader getClassLoader()
In rare cases programmers might need to obtain the class loader that J/Link uses to
load classes from Mathematica. One reason for this is if you want to load a class
in Java code that is found in the special set of extra locations that J/Link's class loader
knows about (such as Java subdirectories of Mathematica application directories; see the
J/Link User Guide for more information on how J/Link finds classes). Another reason is if
want to obtain a class object from a class name and the class has already been loaded
from a special location by J/Link's class loader.
Class cls = Class.forName("Some.class.that.only.JLink.can.find", ml.getClassLoader());
If you are calling this method from a standalone Java program you should first call
enableObjectReferences() to initialize the class loader with the special Mathematica-specific
locations for Java classes.
void setClassLoader(JLinkClassLoader loader)
Advanced programmers might need to specify the class loader that J/Link will use to
load classes from Mathematica. The only reason to do this is if you want the class loader
to have a specific parent loader, because that parent loader has certain capabilities or
can load classes from certain locations that J/Link would otherwise not know about.
KernelLink ml = MathLinkFactory.createKernelLink(...);
ml.discardAnswer();
ml.setClassLoader(new JLinkClassLoader(mySpecialParentClassLoader));
ml.enableObjectReferences();
This method can only be called in a standalone Java program (i.e., not in Java code called
from Mathematica), and should be called before enableObjectReferences().
getClassLoader()
,
enableObjectReferences()
,
JLinkClassLoader
void abortEvaluation()
This method is typically called from a different thread than the one that is performing the computation. That "computation" thread is typically blocking in waitForAnswer() or some other method that is waiting for the result to arrive from Mathematica. If you want to abort the computation so that the main thread does not have to continue waiting, you can call abortEvaluation() on some other thread (perhaps in response to some user action like clicking an "abort" button). The computation will terminate and return the symbol $Aborted. Be aware that Mathematica is not always in a state where it is receptive to abort requests. A quick return of $Aborted is not always guaranteed.
What this method does is simply send an MLABORTMESSAGE to the kernel. It is provided for convenience to shield programmers from such low-level details.
interruptEvaluation()
,
abandonEvaluation()
,
terminateKernel()
void interruptEvaluation()
This method is typically called from a different thread than the one that is performing the computation. That "computation" thread is typically blocking in waitForAnswer() or some other method that is waiting for the result to arrive from Mathematica. If you want to interrupt the computation to provide your users with choices ("abort", "continue", "enter dialog", etc.), you can call interruptEvaluation() on some other thread (perhaps in response to the user clicking an "interrupt" button). Be aware that Mathematica is not always in a state where it is receptive to interrupt requests.
What this method does is simply send an MLINTERRUPTMESSAGE to the kernel. It is provided for convenience to shield programmers from such low-level details.
InterruptDialog
,
abortEvaluation()
,
abandonEvaluation()
,
terminateKernel()
void abandonEvaluation()
This method is typically called from a different thread than the one that is performing the computation. That "computation" thread is typically blocking in waitForAnswer() or some other method that is waiting for the result to arrive from Mathematica. If you want to force that method to return immediately (it will throw a MathLinkException), call abandonEvaluation(). The code in the catch handler for the MathLinkException will find that clearError() returns false, indicating that the link is irrecoverably damaged. You should then call terminateKernel() followed by close().
abortEvaluation()
,
interruptEvaluation()
,
terminateKernel()
void terminateKernel()
Most of the time, when you call close() on a link, the kernel will quit. If the kernel is busy with a computation, however, it will not stop just because the link closes. Use terminateKernel() to force the kernel to quit even though it may be busy. This is not an operating system-level "kill" command, and it is not absolutely guaranteed that the kernel will die immediately.
This method is safe to call from any thread. Any method that is blocking waiting for a result from Mathematica (such as waitForAnswer()) will return immediately and throw a MathLinkException. You will typically call close() immediately after terminateKernel(), as the link will die when the kernel quits.
A typical usage scenario is as follows. You have a thread that is blocking in waitForAnswer() waiting for the result of some computation, and you decide that it must return right away and you are willing to sacrifice the kernel to guarantee this. You then call abandonEvaluation() on a separate thread. This causes waitForAnswer() to immediately throw a MathLinkException. You catch this exception, discover that clearError() returns false indicating that the link is hopeless, and then you call terminateKernel() followed by close(). The reason terminateKernel() is useful here is that because you called abandonEvaluation(), the kernel may still be computing and it may not die when you call close(). You call terminateKernel() to give it a little help.
What this method does is simply send an MLTERMINATEMESSAGE to the kernel. It is provided for convenience to shield programmers from such low-level details.
abortEvaluation()
,
interruptEvaluation()
,
abandonEvaluation()
void print(java.lang.String s)
This method is usable only in Java code that is invoked in a call from Mathematica, as described in Part 1 of the J/Link User Guide. In other words, it is only used in code that is called from a Mathematica session via the "installable Java" mechanism. Programmers who are launching the kernel and controlling it from Java code will have no use for this method.
The KernelLink object on which this method will be called will probably be obtained via
StdLink.getLink()
.
s
- the text to printmessage(String, String)
,
message(String, String[])
void message(java.lang.String symtag, java.lang.String arg)
Use this form for messages that take at most 1 argument to be spliced into their text.
This method is usable only in Java code that is invoked in a call from Mathematica, as described in Part 1 of the J/Link User Guide. In other words, it is only used in code that is called from a Mathematica session via the "installable Java" mechanism. Programmers who are launching the kernel and controlling it from Java code will have no use for this method.
The KernelLink object on which this method will be called will probably be obtained via
StdLink.getLink()
.
symtag
- the message designation, in the usual Symbol::tag stylearg
- a string to be spliced into the message text, in the same way it would be used
by Mathematica's Message function. Pass null if no arguments are needed.message(String, String[])
,
print(String)
void message(java.lang.String symtag, java.lang.String[] args)
Use this form for messages that take more than one argument to be spliced into their text.
This method is usable only in Java code that is invoked in a call from Mathematica, as described in Part 1 of the J/Link User Guide. In other words, it is only used in code that is called from a Mathematica session via the "installable Java" mechanism. Programmers who are launching the kernel and controlling it from Java code will have no use for this method.
The KernelLink object on which this method will be called will probably be obtained via
StdLink.getLink()
.
symtag
- the message designation, in the usual Symbol::tag style,
like Mathematica's Message functionargs
- an array of strings to be spliced into the message text, in the same way as
they are used by Mathematica's Message function.message(String, String)
,
print(String)
void beginManual()
This method is usable only in Java code that is invoked in a call from Mathematica, as described in Part 1 of the J/Link User Guide. In other words, it is only used in code that is called from a Mathematica session via the "installable Java" mechanism. Programmers who are launching the kernel and controlling it from Java code will have no use for this method.
The KernelLink object on which this method will be called will probably be obtained via
StdLink.getLink()
.
The name "beginManual" was chosen instead of, say, "setManual" to emphasize that the link enters a special mode the moment this method is called. To allow the most graceful exception handling, you should delay calling beginManual() until right before you begin to write the result on the link.
boolean wasInterrupted()
This method is usable only in Java code that is invoked in a call from Mathematica, as described in Part 1 of the J/Link User Guide. In other words, it is only used in code that is called from a Mathematica session via the "installable Java" mechanism. Programmers who are launching the kernel and controlling it from Java code will have no use for this method.
When the user tries to interrupt a Mathematica computation that is in the middle of a call into Java, the interrupt request is sent to Java. If a Java method makes no attempt to honor interrupt requests, then after the method call completes J/Link will execute the Mathematica function Abort[], causing the entire computation to end and return the result $Aborted. If you want to detect interrupts within a Java method, for example to break out of a long Java computation, call wasInterrupted() to determine if an interrupt request has been received. If it returns true, then you can simply return from your method, and J/Link will take care of calling Abort[] for you. If the method returns a value, the value will be ignored. For example, you could put code like the following into a time-intensive loop you were running:
KernelLink ml = StdLink.getLink(); if (ml.wasInterrupted()) return;If you want to do something other than call Abort[] in response to the interrupt you should call beginManual(), send back a result manually, and then call clearInterrupt(). The clearInterrupt() method tels J/Link that you have handled the interrupt manually and therefore J/Link should not try to send back Abort[]:
KernelLink ml = StdLink.getLink(); if (ml.wasInterrupted()) { try { ml.beginManual(); ml.put("Interrupted at iteration " + i); ml.clearInterrupt(); } catch (MathLinkException e) {} return; }
clearInterrupt()
void clearInterrupt()
This method is usable only in Java code that is invoked in a call from Mathematica, as described in Part 1 of the J/Link User Guide. In other words, it is only used in code that is called from a Mathematica session via the "installable Java" mechanism. Programmers who are launching the kernel and controlling it from Java code will have no use for this method.
wasInterrupted()
,
beginManual()
J/Link is Copyright (c) 1999-2020, Wolfram Research, Inc. All rights reserved.