Interface MathLink

  • All Known Subinterfaces:
    KernelLink, LoopbackLink

    public interface MathLink
    MathLink is the low-level interface that is the root of all link objects in J/Link. The methods in MathLink correspond roughly to a subset of those in the C-language MathLink API. Most programmers will deal instead with objects of type KernelLink, a higher-level interface that extends MathLink and incorporates the assumption that the program on the other side of the link is a Mathematica kernel.

    You create objects of type MathLink via the MathLinkFactory.createLink() method. Again, though, most programmers will use KernelLink instead of MathLink.

    Most MathLink methods throw a MathLinkException if a link-related error occurs. Examples would be calling endPacket() before sending a complete expression, or calling getFunction() when an integer is waiting on the link.

    For additional information about these methods, see the J/Link User Guide, and also the MathLink documentation in the Mathematica book. Most of these methods are substantially similar, if not identical, to their C counterparts as documented in the book.

    See Also:
    KernelLink, MathLinkFactory
    • Method Summary

      All Methods Instance Methods Abstract Methods Deprecated Methods 
      Modifier and Type Method Description
      void activate()
      Same as connect().
      boolean addMessageHandler​(java.lang.Class cls, java.lang.Object obj, java.lang.String methName)
      Specifies the Java method you want called as a message handler.
      int bytesToGet()
      Returns the number of bytes that remain to be read in the element that is currently being read in textual form.
      int bytesToPut()
      Gives the number of bytes that remain to be sent in the element that is currently being sent in textual form.
      int checkFunction​(java.lang.String f)
      Reads a function name and argument count and compares the function name with f.
      void checkFunctionWithArgCount​(java.lang.String f, int argCount)
      Reads a function name and argument count and compares the function name with f and the argument count with argCount.
      boolean clearError()
      Clears the link error condition, if possible.
      void close()
      Closes the link.
      void connect()
      Connects the link, if it has not already been connected.
      void connect​(long timeoutMillis)
      Connects the link, but waits at most timeoutMillis for a response from the other side.
      long createMark()
      Creates a mark at the current point in the incoming MathLink data stream.
      void destroyMark​(long mark)
      Destroys a mark.
      void endPacket()
      Call it when you are finished writing the contents of a single packet.
      int error()
      Gives the code corresponding to the current error state of the link.
      java.lang.String errorMessage()
      Gives a textual message describing the current error.
      void flush()
      Immediately transmits any data buffered for sending over the link.
      int getArgCount()
      Reads the argument count of an expression being read manually.
      java.lang.Object getArray​(int type, int depth)
      Reads an array of the specified type and depth.
      java.lang.Object getArray​(int type, int depth, java.lang.String[] heads)
      Reads an array of the specified type and depth and records the heads at each level.
      boolean getBoolean()
      Reads the Mathematica symbols True or False as a boolean.
      boolean[] getBooleanArray1()
      Reads a list as a one-dimensional array of booleans.
      boolean[][] getBooleanArray2()
      Reads an array as a two-dimensional array of booleans.
      byte[] getByteArray1()
      Reads a list or array as a one-dimensional array of bytes.
      byte[][] getByteArray2()
      Reads an array as a two-dimensional array of bytes.
      byte[] getByteString​(int missing)
      Reads a Mathematica string as an array of bytes.
      char[] getCharArray1()
      Reads a list or array as a one-dimensional array of chars.
      char[][] getCharArray2()
      Reads an array as a two-dimensional array of chars.
      java.lang.Object getComplex()
      Reads a complex number.
      java.lang.Object[] getComplexArray1()
      Reads a list as a one-dimensional array of complex numbers.
      java.lang.Object[][] getComplexArray2()
      Reads a matrix as a two-dimensional array of complex numbers.
      java.lang.Class getComplexClass()
      Gives the Java class that you have specified to map to Mathematica's Complex numbers.
      byte[] getData​(int len)
      Gets a specified number of bytes in the textual form of the expression currently being read.
      double getDouble()
      Reads a Mathematica real number or integer as a double.
      double[] getDoubleArray1()
      Reads a list or array as a one-dimensional array of doubles.
      double[][] getDoubleArray2()
      Reads an array as a two-dimensional array of doubles.
      Expr getExpr()
      Reads an expression from the link and creates an Expr from it.
      float[] getFloatArray1()
      Reads a list or array as a one-dimensional array of floats.
      float[][] getFloatArray2()
      Reads an array as a two-dimensional array of floats.
      MLFunction getFunction()
      Reads a function name and argument count.
      int[] getIntArray1()
      Reads a list or array as a one-dimensional array of ints.
      int[][] getIntArray2()
      Reads an array as a two-dimensional array of ints.
      int getInteger()
      Reads a Mathematica integer as an int.
      long[] getLongArray1()
      Reads a list as a one-dimensional array of longs.
      long[][] getLongArray2()
      Reads an array as a two-dimensional array of longs.
      long getLongInteger()
      Reads a Mathematica integer as a long.
      int getMessage()
      Deprecated. 
      int getNext()
      Gives the type of the next element in the expression currently being read.
      short[] getShortArray1()
      Reads a list or array as a one-dimensional array of shorts.
      short[][] getShortArray2()
      Reads an array as a two-dimensional array of shorts.
      java.lang.String getString()
      Reads a Mathematica character string.
      java.lang.String[] getStringArray1()
      Reads a list as a one-dimensional array of strings.
      java.lang.String[][] getStringArray2()
      Reads an array as a two-dimensional array of strings.
      java.lang.String getSymbol()
      Reads a Mathematica symbol as a string.
      int getType()
      Gives the type of the current element in the expression currently being read.
      boolean messageReady()
      Deprecated. 
      java.lang.String name()
      Gives the name of the link.
      void newPacket()
      Discards the current packet, if it has been partially read.
      int nextPacket()
      "Opens" the next packet arriving on the link.
      Expr peekExpr()
      Creates an Expr from the current expression, but does not drain it off the link.
      void put​(boolean b)
      Sends the boolean value as the Mathematica symbol True or False.
      void put​(double d)
      Sends a double value.
      void put​(int i)
      Sends an integer value.
      void put​(long i)
      Sends a long value.
      void put​(java.lang.Object obj)
      Sends an object, including strings and arrays.
      void put​(java.lang.Object obj, java.lang.String[] heads)
      Sends an array object.
      void putArgCount​(int argCount)
      Specifies the argument count for a composite expression being sent manually.
      void putByteString​(byte[] data)
      Sends an array of bytes to Mathematica as a string.
      void putData​(byte[] data)
      Used for sending elements in textual form.
      void putData​(byte[] data, int len)
      An alternative form of putData() that lets you specify how many bytes from the array should be sent, rather than just sending the whole thing.
      void putFunction​(java.lang.String f, int argCount)
      Sends a function name and argument count.
      void putMessage​(int msg)
      Sends a low-level MathLink message.
      void putNext​(int type)
      Identifies the type of data element that is to be sent.
      void putSize​(int size)
      Specifies the size in bytes of an element being sent in textual form.
      void putSymbol​(java.lang.String s)
      Sends a symbol name.
      boolean ready()
      Indicates whether the link has data waiting to be read.
      boolean removeMessageHandler​(java.lang.String methName)
      Removes a message handler you previously set up with addMessageHandler.
      void seekMark​(long mark)
      Resets the current position in the incoming MathLink data stream to an earlier point.
      boolean setComplexClass​(java.lang.Class cls)
      Specifies the class you want to map to Mathematica's Complex numbers.
      void setError​(int err)
      Sets the link's error state to the specified value.
      boolean setYieldFunction​(java.lang.Class cls, java.lang.Object obj, java.lang.String methName)
      Sets the Java method you want called as a yield function.
      void transferExpression​(MathLink source)
      Writes a complete expression from the link source to this link.
      void transferToEndOfLoopbackLink​(LoopbackLink source)
      Writes the entire contents of the LoopbackLink source to this link.
    • Method Detail

      • close

        void close()
        Closes the link. Always call close() on every link when you are done using it.
      • connect

        void connect()
              throws MathLinkException
        Connects the link, if it has not already been connected. There is a difference between opening a link (which is what the MathLinkFactory methods createLink() and createKernelLink() do) and connecting it, which verifies that it is alive and ready for data transfer.

        All the methods that read from the link will connect it if necessary. The connect() method lets you deliberately control the point in the program where the connection occurs, without having to read anything.

        Throws:
        MathLinkException
      • connect

        void connect​(long timeoutMillis)
              throws MathLinkException
        Connects the link, but waits at most timeoutMillis for a response from the other side. If the timeout passes, a MathLinkException is thrown. This is a handy way to prevent your thread from hanging indefinitely if there is a problem in connecting. Such problems are not hard to generate--for example, if the user launches a process other than a Mathematica kernel in their arguments to MathLinkFactory.createKernelLink(), the Java side will likely hang at the stage of connecting. If the timeout passes and an exception is thrown, the link cannot be salvaged and should be closed. Make sure you give adequate time for the kernel to launch.
        Parameters:
        timeoutMillis - the number of milliseconds to wait
        Throws:
        MathLinkException
        See Also:
        connect()
      • name

        java.lang.String name()
                       throws MathLinkException
        Gives the name of the link. For typical links, the name of a listen-mode link can be used by the other side to connect to.
        Throws:
        MathLinkException
      • newPacket

        void newPacket()
        Discards the current packet, if it has been partially read. Has no effect if the previous packet was fully read.

        This is a useful cleanup function. You can call it when you are finished examining the contents of a packet that was opened with nextPacket() or waitForAnswer(), whether you have read the entire packet contents or not. You can be sure that the link is then in a state where you are ready to read the next packet.

        It is also frequently used in a catch block for a MathLinkException, to clear off any unread data in a packet before returning to the normal program flow.

        See Also:
        nextPacket()
      • nextPacket

        int nextPacket()
                throws MathLinkException
        "Opens" the next packet arriving on the link. It is an error to call nextPacket() while the current packet has unread data; use newPacket() to discard the current packet first.

        Most programmers will use this method rarely, if ever. J/Link provides higher-level functions in the KernelLink interface that hide these low-level details of the packet loop.

        Returns:
        the packet type (e.g., RETURNPKT, TEXTPKT).
        Throws:
        MathLinkException
        See Also:
        newPacket()
      • endPacket

        void endPacket()
                throws MathLinkException
        Call it when you are finished writing the contents of a single packet.

        Calling endPacket() is not strictly necessary, but it is good style, and it allows J/Link to immediately generate a MathLinkException if you are not actually finished with writing the data you promised to send.

        Throws:
        MathLinkException
      • error

        int error()
        Gives the code corresponding to the current error state of the link.
        Returns:
        the error code; will be MLEOK if no error.
        See Also:
        errorMessage(), clearError()
      • clearError

        boolean clearError()
        Clears the link error condition, if possible. After an error has occurred, and a MathLinkException has been caught, you must call clearError() before doing anything else with the link.
        Returns:
        true, if the error state was cleared; false, if the error could not be cleared. If false, you must close the link.
      • errorMessage

        java.lang.String errorMessage()
        Gives a textual message describing the current error.
        Returns:
        the error message
        See Also:
        error()
      • setError

        void setError​(int err)
        Sets the link's error state to the specified value. Afterwards, error() will return this value. Very few programmers will have any need for this method.
        Parameters:
        err - the error code
      • ready

        boolean ready()
               throws MathLinkException
        Indicates whether the link has data waiting to be read. In other words, it tells whether the next call that reads data will block or not.
        Returns:
        true, if data is waiting; false otherwise
        Throws:
        MathLinkException
      • flush

        void flush()
            throws MathLinkException
        Immediately transmits any data buffered for sending over the link.

        Any calls that read from the link will flush it, so you only need to call flush() manually if you want to make sure data is sent right away even though you are not reading from the link immediately. Calls to ready() will not flush the link, so if you are sending something and then polling ready() waiting for the result to arrive (as opposed to just calling nextPacket() or waitForAnswer()), you must call flush to ensure that the data is sent.

        Throws:
        MathLinkException
      • getNext

        int getNext()
             throws MathLinkException
        Gives the type of the next element in the expression currently being read.

        To check the type of a partially read element without advancing to the next element, use getType().

        Returns:
        one of MLTKINT, MLTKREAL, MLTKSTR, MLTKSYM, MLTKFUNC
        Throws:
        MathLinkException
      • getType

        int getType()
             throws MathLinkException
        Gives the type of the current element in the expression currently being read.

        Unlike getNext(), getType() will not advance to the next element if the current element has only been partially read.

        Returns:
        one of MLTKINT, MLTKREAL, MLTKSTR, MLTKSYM, MLTKFUNC
        Throws:
        MathLinkException
        See Also:
        getNext()
      • putNext

        void putNext​(int type)
              throws MathLinkException
        Identifies the type of data element that is to be sent.

        putNext() is rarely needed. The two most likely uses are to put expressions whose heads are not mere symbols (e.g., Derivative[2][f]) or to put data in textual form. Calls to putNext() must be followed by putSize() and putData(), or by putArgCount() for the MLTKFUNC type. Here is how you could send Derivative[2][f]:

         ml.putNext(MathLink.MLTKFUNC);  // The func we are putting has head Derivative[2], arg f
         ml.putArgCount(1);  // this 1 is for the 'f'
         ml.putNext(MathLink.MLTKFUNC);  // The func we are putting has head Derivative, arg 2
         ml.putArgCount(1);  // this 1 is for the '2'
         ml.putSymbol("Derivative");
         ml.put(2);
         ml.putSymbol("f");
        Parameters:
        type - one of MLTKINT, MLTKREAL, MLTKSTR, MLTKSYM, MLTKFUNC
        Throws:
        MathLinkException
        See Also:
        putSize(int), putData(byte[]), putArgCount(int)
      • getArgCount

        int getArgCount()
                 throws MathLinkException
        Reads the argument count of an expression being read manually.

        This method can be used after getNext() or getType() returns the value MLTKFUNC. The argument count is always followed by the head of the expression. The head is followed by the arguments; the argument count tells how many there will be.

        Returns:
        the number of arguments in the expression being read
        Throws:
        MathLinkException
        See Also:
        getNext(), getType()
      • putArgCount

        void putArgCount​(int argCount)
                  throws MathLinkException
        Specifies the argument count for a composite expression being sent manually.

        Use it after a call to putNext() with the MLTKFUNC type.

        Parameters:
        argCount - the number of aruments in the expression being sent
        Throws:
        MathLinkException
        See Also:
        putNext(int)
      • putSize

        void putSize​(int size)
              throws MathLinkException
        Specifies the size in bytes of an element being sent in textual form.

        A typical sequence would be putNext(), followed by putSize(), then putData().

        Parameters:
        size - the size of the data, in bytes, that will be written with the following putData()
        Throws:
        MathLinkException
        See Also:
        putData(byte[]), putNext(int)
      • bytesToPut

        int bytesToPut()
                throws MathLinkException
        Gives the number of bytes that remain to be sent in the element that is currently being sent in textual form.

        After you have called putSize(), the link knows how many bytes you have promised to send. This method lets you determine how many you still need to send, in the unlikely event that you lose track after a series of putData() calls.

        Returns:
        the number of bytes that remain to be sent
        Throws:
        MathLinkException
        See Also:
        putSize(int), putData(byte[])
      • bytesToGet

        int bytesToGet()
                throws MathLinkException
        Returns the number of bytes that remain to be read in the element that is currently being read in textual form.

        Lets you keep track of your progress reading an element through a series of getData() calls.

        Returns:
        the number of bytes that remain to be read in the current element
        Throws:
        MathLinkException
        MathLinkException
        See Also:
        getData(int)
      • putData

        void putData​(byte[] data)
              throws MathLinkException
        Used for sending elements in textual form. After calling putNext() and putSize(), a series of putData() calls are used to send the actual data.

        The so-called "textual" means of sending data is rarely used. Its main use is to allow a very large string to be sent, where the string data is not held in a single String object. The most important use of this technique in the C-language MathLink API was to send integers and reals that were too large to fit into an int or double. This use is unnecessary in J/Link, since Java has BigInteger and BigDecimal classes, and these objects can be sent directly with put().

        Parameters:
        data - the textual representation of the data
        Throws:
        MathLinkException
        See Also:
        putNext(int), putSize(int)
      • putData

        void putData​(byte[] data,
                     int len)
              throws MathLinkException
        An alternative form of putData() that lets you specify how many bytes from the array should be sent, rather than just sending the whole thing.
        Parameters:
        data -
        len -
        Throws:
        MathLinkException
        See Also:
        putData(byte[])
      • getData

        byte[] getData​(int len)
                throws MathLinkException
        Gets a specified number of bytes in the textual form of the expression currently being read. The returned array will have a length of at most len.

        You can use bytesToGet() to determine if more getData() calls are needed to completely read the element.

        Parameters:
        len - the maximum number of bytes to read
        Returns:
        the data read
        Throws:
        MathLinkException
        See Also:
        bytesToGet(), getNext(), getType()
      • getString

        java.lang.String getString()
                            throws MathLinkException
        Reads a Mathematica character string.

        Because both Java and Mathematica strings are in Unicode, the read string is an exact match to its Mathematica representation.

        Returns:
        the string that was read
        Throws:
        MathLinkException
      • getByteString

        byte[] getByteString​(int missing)
                      throws MathLinkException
        Reads a Mathematica string as an array of bytes.

        In contrast with getString(), this method strips the incoming (16-bit Unicode) character data into single-byte representation. Characters that cannot be represented faithfully in single-byte form are replaced by the byte specified by the missing parameter. This method is primarily useful if you know the incoming data contains only ASCII characters and you want the data in the form of a byte array.

        Parameters:
        missing - the byte to replace non-ASCII characters with
        Returns:
        the data that was read
        Throws:
        MathLinkException
        See Also:
        getString()
      • putByteString

        void putByteString​(byte[] data)
                    throws MathLinkException
        Sends an array of bytes to Mathematica as a string.

        Use this instead of put() if you have string data in the form of a byte array. In the C-language MathLink API, MLPutByteString was useful because the more obviously-named MLPutString required a specially-encoded string. Because Java strings and Mathematica strings are both Unicode, put() works in J/Link without requiring special encoding. Thus, putByteString() has little use.

        Parameters:
        data - the string data to send
        Throws:
        MathLinkException
        See Also:
        put(Object)
      • getSymbol

        java.lang.String getSymbol()
                            throws MathLinkException
        Reads a Mathematica symbol as a string.

        Because Java strings and Mathematica symbols are in Unicode, the read string is an exact match to its Mathematica representation.

        Returns:
        the symbol
        Throws:
        MathLinkException
        See Also:
        getString()
      • putSymbol

        void putSymbol​(java.lang.String s)
                throws MathLinkException
        Sends a symbol name.

        Both Java strings and Mathematica symbols are in Unicode, so you can send symbols with the full Unicode character set.

        Parameters:
        s - the symbol name
        Throws:
        MathLinkException
      • getBoolean

        boolean getBoolean()
                    throws MathLinkException
        Reads the Mathematica symbols True or False as a boolean. More precisely, it returns true if the symbol True is read, and false if False (or any other non-True symbol) is read. If you want to make sure that either True or False is on the link, don't use getBoolean(); instead, read the symbol with getSymbol() and test its value yourself.
        Returns:
        the boolean read
        Throws:
        MathLinkException
      • put

        void put​(boolean b)
          throws MathLinkException
        Sends the boolean value as the Mathematica symbol True or False.
        Parameters:
        b - the value to send
        Throws:
        MathLinkException
      • getBooleanArray1

        boolean[] getBooleanArray1()
                            throws MathLinkException
        Reads a list as a one-dimensional array of booleans.

        The expression being read must be a list or other depth-1 expression of the symbols True and False. The "1" suffix in the method name indicates that the returned array has depth 1.

        The expression does not need to have head List. In other words, it could be List[False, True] or Foo[True, True]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not a depth-1 array of True and False
        See Also:
        getArray(int, int)
      • getBooleanArray2

        boolean[][] getBooleanArray2()
                              throws MathLinkException
        Reads an array as a two-dimensional array of booleans.

        The expression being read must be a matrix of the symbols True and False. The "2" suffix in the method name indicates that the returned array has depth 2.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[True, False], List[True, True]] or Foo[Bar[True, False], Bar[True, True]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not a 2-deep array of True and False
        See Also:
        getArray(int, int)
      • getByteArray1

        byte[] getByteArray1()
                      throws MathLinkException
        Reads a list or array as a one-dimensional array of bytes.

        The expression being read must be a list or deeper array of integers. Values outside the range of a byte are converted via casting. The "1" suffix in the method name indicates that the returned array has depth 1. If the arriving expression has depth greater than 1 (e.g., it is a matrix), it will be flattened to a 1-dimensional array.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1, 2], List[3, 4]] or Foo[Bar[1, 2], Bar[3, 4]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an array of integers
        See Also:
        getArray(int, int)
      • getByteArray2

        byte[][] getByteArray2()
                        throws MathLinkException
        Reads an array as a two-dimensional array of bytes.

        The expression being read must be a matrix or deeper array of integers. Values outside the range of a byte are converted via casting. The "2" suffix in the method name indicates that the returned array has depth 2. If the arriving expression has depth greater than 2, it will be flattened to a 2-dimensional array. If the arriving expression has a depth less than 2 (i.e., it is a flat list), a MathLinkException will be thrown.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1, 2], List[3, 4]] or Foo[Bar[1, 2], Bar[3, 4]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an array of integers
        See Also:
        getArray(int, int)
      • getCharArray1

        char[] getCharArray1()
                      throws MathLinkException
        Reads a list or array as a one-dimensional array of chars.

        The expression being read must be a list or deeper array of integers. Values outside the range of a char are converted via casting. The "1" suffix in the method name indicates that the returned array has depth 1. If the arriving expression has depth greater than 1 (e.g., it is a matrix), it will be flattened to a 1-dimensional array.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1, 2], List[3, 4]] or Foo[Bar[1, 2], Bar[3, 4]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an array of integers
        See Also:
        getArray(int, int)
      • getCharArray2

        char[][] getCharArray2()
                        throws MathLinkException
        Reads an array as a two-dimensional array of chars.

        The expression being read must be a matrix or deeper array of integers. Values outside the range of a char are converted via casting. The "2" suffix in the method name indicates that the returned array has depth 2. If the arriving expression has depth greater than 2, it will be flattened to a 2-dimensional array. If the arriving expression has a depth less than 2 (i.e., it is a flat list), a MathLinkException will be thrown.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1, 2], List[3, 4]] or Foo[Bar[1, 2], Bar[3, 4]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an array of integers
        See Also:
        getArray(int, int)
      • getShortArray1

        short[] getShortArray1()
                        throws MathLinkException
        Reads a list or array as a one-dimensional array of shorts.

        The expression being read must be a list or deeper array of integers. Values outside the range of a short are converted via casting. The "1" suffix in the method name indicates that the returned array has depth 1. If the arriving expression has depth greater than 1 (e.g., it is a matrix), it will be flattened to a 1-dimensional array.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1, 2], List[3, 4]] or Foo[Bar[1, 2], Bar[3, 4]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an array of integers
        See Also:
        getArray(int, int)
      • getShortArray2

        short[][] getShortArray2()
                          throws MathLinkException
        Reads an array as a two-dimensional array of shorts.

        The expression being read must be a matrix or deeper array of integers. Values outside the range of a short are converted via casting. The "2" suffix in the method name indicates that the returned array has depth 2. If the arriving expression has depth greater than 2, it will be flattened to a 2-dimensional array. If the arriving expression has a depth less than 2 (i.e., it is a flat list), a MathLinkException will be thrown.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1, 2], List[3, 4]] or Foo[Bar[1, 2], Bar[3, 4]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an array of integers
        See Also:
        getArray(int, int)
      • getIntArray1

        int[] getIntArray1()
                    throws MathLinkException
        Reads a list or array as a one-dimensional array of ints.

        The expression being read must be a list or deeper array of integers. The "1" suffix in the method name indicates that the returned array has depth 1. If the arriving expression has depth greater than 1 (e.g., it is a matrix), it will be flattened to a 1-dimensional array.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1, 2], List[3, 4]] or Foo[Bar[1, 2], Bar[3, 4]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an array of integers
        See Also:
        getArray(int, int)
      • getIntArray2

        int[][] getIntArray2()
                      throws MathLinkException
        Reads an array as a two-dimensional array of ints.

        The expression being read must be a matrix or deeper array of integers. The "2" suffix in the method name indicates that the returned array has depth 2. If the arriving expression has depth greater than 2, it will be flattened to a 2-dimensional array. If the arriving expression has a depth less than 2 (i.e., it is a flat list), a MathLinkException will be thrown.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1, 2], List[3, 4]] or Foo[Bar[1, 2], Bar[3, 4]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an array of integers
        See Also:
        getArray(int, int)
      • getLongArray1

        long[] getLongArray1()
                      throws MathLinkException
        Reads a list as a one-dimensional array of longs.

        The expression being read must be a list or other depth-1 expression of integers. The "1" suffix in the method name indicates that the returned array has depth 1.

        The expression does not need to have head List. In other words, it could be List[1, 2] or Foo[1, 2]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not a depth-1 array of integers
        See Also:
        getArray(int, int)
      • getLongArray2

        long[][] getLongArray2()
                        throws MathLinkException
        Reads an array as a two-dimensional array of longs.

        The expression being read must be a matrix of integers. The "2" suffix in the method name indicates that the returned array has depth 2.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1, 2], List[3, 4]] or Foo[Bar[1, 2], Bar[3, 4]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not a depth-2 array of integers
        See Also:
        getArray(int, int)
      • getFloatArray1

        float[] getFloatArray1()
                        throws MathLinkException
        Reads a list or array as a one-dimensional array of floats.

        The expression being read must be a list or deeper array of real numbers or integers. The "1" suffix in the method name indicates that the returned array has depth 1. If the arriving expression has depth greater than 1 (e.g., it is a matrix), it will be flattened to a 1-dimensional array.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1., 2.], List[3., 4.]] or Foo[Bar[1., 2.], Bar[3., 4.]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an array of reals or integers
        See Also:
        getArray(int, int)
      • getFloatArray2

        float[][] getFloatArray2()
                          throws MathLinkException
        Reads an array as a two-dimensional array of floats.

        The expression being read must be a matrix or deeper array of real numbers or integers. The "2" suffix in the method name indicates that the returned array has depth 2. If the arriving expression has depth greater than 2, it will be flattened to a 2-dimensional array. If the arriving expression has a depth less than 2 (i.e., it is a flat list), a MathLinkException will be thrown.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1., 2.], List[3., 4.]] or Foo[Bar[1., 2.], Bar[3., 4.]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an of array reals or integers
        See Also:
        getArray(int, int)
      • getDoubleArray1

        double[] getDoubleArray1()
                          throws MathLinkException
        Reads a list or array as a one-dimensional array of doubles.

        The expression being read must be a list or deeper array of real numbers or integers. The "1" suffix in the method name indicates that the returned array has depth 1. If the arriving expression has depth greater than 1 (e.g., it is a matrix), it will be flattened to a 1-dimensional array.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1., 2.], List[3., 4.]] or Foo[Bar[1., 2.], Bar[3., 4.]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an array of reals or integers
        See Also:
        getArray(int, int)
      • getDoubleArray2

        double[][] getDoubleArray2()
                            throws MathLinkException
        Reads an array as a two-dimensional array of doubles.

        The expression being read must be a matrix or deeper array of real numbers or integers. The "2" suffix in the method name indicates that the returned array has depth 2. If the arriving expression has depth greater than 2, it will be flattened to a 2-dimensional array. If the arriving expression has a depth less than 2 (i.e., it is a flat list), a MathLinkException will be thrown.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1., 2.], List[3., 4.]] or Foo[Bar[1., 2.], Bar[3., 4.]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not an array of reals or integers
        See Also:
        getArray(int, int)
      • getStringArray1

        java.lang.String[] getStringArray1()
                                    throws MathLinkException
        Reads a list as a one-dimensional array of strings.

        The expression being read must be a list or other depth-1 expression of strings or symbols. The "1" suffix in the method name indicates that the returned array has depth 1.

        The expression does not need to have head List. In other words, it could be List["A", "B"] or Foo["A", "B"]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not a depth-1 array of strings or symbols
        See Also:
        getArray(int, int)
      • getStringArray2

        java.lang.String[][] getStringArray2()
                                      throws MathLinkException
        Reads an array as a two-dimensional array of strings.

        The expression being read must be a matrix of strings or symbols. The "2" suffix in the method name indicates that the returned array has depth 2.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List["A", "B"], List["C", D"]] or Foo[Bar["A", "B"], Bar["C", "D"]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read
        Throws:
        MathLinkException - if the incoming expression is not a matrix of strings or symbols
        See Also:
        getArray(int, int)
      • getComplexArray1

        java.lang.Object[] getComplexArray1()
                                     throws MathLinkException
        Reads a list as a one-dimensional array of complex numbers.

        The expression being read must be a list or other depth-1 expression of Complex. The "1" suffix in the method name indicates that the returned array has depth 1.

        This method will read the expression, but return null, if no Java class has yet been established to use for complex numbers by calling setComplexClass.

        The expression does not need to have head List. In other words, it could be List[1+I, 2-I] or Foo[1+I, 2-I]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read, or null if no Java class has been declared for complex numbers via setComplexClass()
        Throws:
        MathLinkException - if the incoming expression is not a depth-1 array of Complex
        See Also:
        setComplexClass(Class), getArray(int, int)
      • getComplexArray2

        java.lang.Object[][] getComplexArray2()
                                       throws MathLinkException
        Reads a matrix as a two-dimensional array of complex numbers.

        The expression being read must be a matrix of Complex. The "2" suffix in the method name indicates that the returned array has depth 2.

        The expression does not need to have head List. It can have any heads, at any depth. In other words, it could be List[List[1+I, 2-I], List[3+I, 4-I]] or Foo[Bar[1+I, 2-I], Bar[3+I, 4-I]]. The information about the heads is lost; if you need this information you will need to either use getArray(int, int, String[]) or read the expression as an Expr and examine it using the Expr methods.

        Returns:
        the array read, or null if no Java class has been declared for complex numbers via setComplexClass()
        Throws:
        MathLinkException - if the incoming expression is not a matrix of Complex
        See Also:
        setComplexClass(Class), getArray(int, int)
      • getArray

        java.lang.Object getArray​(int type,
                                  int depth)
                           throws MathLinkException
        Reads an array of the specified type and depth.

        The getXXXArrayN methods are all just convenience methods that call this method. Use this method instead when you want to read an array of dimensionality deeper than 2. Cast the result of this method to the desired array type, as in:

             int[][][] result = (int[][][]) ml.getArray(TYPE_INT, 3); 
        For the types TYPE_BYTE, TYPE_CHAR, TYPE_SHORT, TYPE_INT, TYPE_FLOAT, and TYPE_DOUBLE, if the expression has depth greater than depth, it will be flattened to a Java array of dimension depth. If the expression has a depth less than depth, a MathLinkException will be thrown.

        The maximum depth supported is 5.

        The expression does not need to have head List. It can have any heads, at any depth, and the heads do not have to agree at each depth, meaning that you could read the expression {foo[1, 2], bar[3, 4]} as an int[][]. The information about the heads is lost; if you need this information you can use the alternative signature getArray(int type, int depth, String[] heads), or read the expression as an Expr and examine it using the Expr methods.

        Parameters:
        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 array
        Returns:
        the array read, or null if type is TYPE_COMPLEX and no Java class has been declared for complex numbers via setComplexClass()
        Throws:
        MathLinkException - if the incoming expression is not an array of the requested type or is not as deep as requested
        MathLinkException
        See Also:
        getArray(int, int, String[])
      • getArray

        java.lang.Object getArray​(int type,
                                  int depth,
                                  java.lang.String[] heads)
                           throws MathLinkException
        Reads an array of the specified type and depth and records the heads at each level.

        Identical to getArray(int type, int depth), except that this form fills a String array with the heads of the expression found at each level. To use this method, allocate a String array of length 'depth' and pass it in. For example:

         // Assume that the expression {foo[1, 2], foo[3, 4]} is waiting on the link.
         String[] heads = new String[2];
         int[][] intArray2D = (int[][]) ml.getArray(MathLink.TYPE_INT, 2, heads);
         // Now heads[0] is "List" and heads[1] is "foo".
        This method does not enforce a requirement that the heads be identical across a level. If the expression looks like {foo[1, 2], bar[3, 4]} then the heads array would become {"List", "foo"}, ignoring the fact that foo was not the head of every subexpression at level 1. In other words, if heads[i] is "foo", then it is only guaranteed that some expression at level i had head foo, not that all of them did. If you want to be absolutely sure about the heads of every subpart, read the expression as an Expr and use the Expr methods to inspect it.
        Parameters:
        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 array
        heads - an array of length 'depth' that will be filled with the heads at each level
        Returns:
        the array read, or null if type is TYPE_COMPLEX and no Java class has been declared for complex numbers via setComplexClass()
        Throws:
        MathLinkException - if the incoming expression is not an array of the requested type, or is not as deep as requested
        Since:
        2.0
        See Also:
        getArray(int, int)
      • putFunction

        void putFunction​(java.lang.String f,
                         int argCount)
                  throws MathLinkException
        Sends a function name and argument count.

        Follow this with calls to put the arguments.

        Parameters:
        f - the function name
        argCount - the number of arguments to follow
        Throws:
        MathLinkException
      • checkFunction

        int checkFunction​(java.lang.String f)
                   throws MathLinkException
        Reads a function name and argument count and compares the function name with f. If they do not match, a MathLinkException is thrown.

        Similar to getFunction() in that it reads the name and argument count off the link. Use it in situations where you want an error to occur if the function is not what you expect.

        Parameters:
        f - the function name that you are expecting
        Returns:
        the argument count
        Throws:
        MathLinkException - if the current expression is not a function, or if it does not have the specified name
        See Also:
        checkFunctionWithArgCount(String, int)
      • checkFunctionWithArgCount

        void checkFunctionWithArgCount​(java.lang.String f,
                                       int argCount)
                                throws MathLinkException
        Reads a function name and argument count and compares the function name with f and the argument count with argCount. If they do not match, a MathLinkException is thrown.

        Similar to getFunction() in that it reads the name and argument count off the link. Use it in situations where you want an error to occur if the function is not what you expect.

        Parameters:
        f - the function name that you are expecting
        argCount - the argument count that you are expecting
        Throws:
        MathLinkException - if the current expression is not a function, or if it does not have the specified name
        See Also:
        checkFunction(String)
      • getComplex

        java.lang.Object getComplex()
                             throws MathLinkException
        Reads a complex number. This can be an integer, real, or a Mathematica expression with head Complex. You must first specify a Java class for complex numbers using setComplexClass().

        This method will read the number, but return null, if no Java class has yet been established to use for complex numbers.

        Returns:
        an object of the class you have specified to map to Mathematica Complex numbers, or null if you have not specified any class (using setComplexClass()).
        Throws:
        MathLinkException - if the current expression is not an integer, real, or Mathematica Complex.
        See Also:
        setComplexClass(Class)
      • getExpr

        Expr getExpr()
              throws MathLinkException
        Reads an expression from the link and creates an Expr from it.

        The returned Expr can be examined and manipulated later.

        Returns:
        the Expr read
        Throws:
        MathLinkException
        See Also:
        peekExpr()
      • peekExpr

        Expr peekExpr()
               throws MathLinkException
        Creates an Expr from the current expression, but does not drain it off the link.

        Like getExpr(), but peekExpr() does not actually remove anything from the link. In other words, it leaves the link in the same state it was in before peekExpr() was called.

        Returns:
        the Expr read
        Throws:
        MathLinkException
        See Also:
        getExpr()
      • getMessage

        int getMessage()
                throws MathLinkException
        Deprecated.
        Reads a low-level MathLink message.

        This method no longer functions in J/Link 2.0. You must use addMessageHandler() if you want to be able to receive messages from Mathematica.

        Returns:
        the message read; will most likely be one of MLINTERRUPTMESSAGE or MLABORTMESSAGE
        Throws:
        MathLinkException
        See Also:
        addMessageHandler(Class, Object, String)
      • putMessage

        void putMessage​(int msg)
                 throws MathLinkException
        Sends a low-level MathLink message.

        To abort a Mathematica computation, use putMessage(MLABORTMESSAGE). If a computation is successfully aborted, it will return the symbol $Aborted.

        Do not confuse this type of message, used mainly for communicating requests to interrupt or abort computations, with Mathematica warning messages, which are unrelated.

        Parameters:
        msg - the message to send; will be one of MLABORTMESSAGE or MLINTERRUPTMESSAGE. Most users will only be concerned with MLABORTMESSAGE.
        Throws:
        MathLinkException
      • messageReady

        boolean messageReady()
                      throws MathLinkException
        Deprecated.
        Tells whether a low-level MathLink message has arrived.

        This method no longer functions in J/Link 2.0. You must use addMessageHandler() if you want to be able to receive messages from Mathematica.

        Returns:
        true if a message is waiting to be read with getMessage(); false otherwise
        Throws:
        MathLinkException
        See Also:
        addMessageHandler(Class, Object, String)
      • createMark

        long createMark()
                 throws MathLinkException
        Creates a mark at the current point in the incoming MathLink data stream.

        Marks can returned to later, to re-read data. A common use is to create a mark, call some method for reading data, and if a MathLinkException is thrown, seek back to the mark and try a different method of reading the data.

        Make sure to always call destroyMark() on any marks you create. Failure to do so will cause a memory leak.

        Some of the usefulness of marks in the C-language MathLink API is obviated by J/Link's Expr class.

        Returns:
        the mark. You cannot do anything with this value except use it in seekMark() or destroyMark(); it has no meaning as a number.
        Throws:
        MathLinkException
        See Also:
        seekMark(long), destroyMark(long)
      • seekMark

        void seekMark​(long mark)
        Resets the current position in the incoming MathLink data stream to an earlier point.
        Parameters:
        mark - the mark, created by createMark(), that identifies the desired position to reset to
        See Also:
        createMark(), seekMark(long)
      • destroyMark

        void destroyMark​(long mark)
        Destroys a mark. Always call destroyMark() on any marks you create with createMark().
        Parameters:
        mark - the mark to destroy
      • put

        void put​(java.lang.Object obj)
          throws MathLinkException
        Sends an object, including strings and arrays.

        Only a limited set of Java objects can be usefully sent across a link with this method. These are objects whose "values" have a meaningful representation in Mathematica:

         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 Complex
        All other objects have no meaningful representation in Mathematica. For these objects, the relatively useless obj.toString() is sent. The put(Object) method in the KernelLink interface will put these objects "by reference".
        Parameters:
        obj - the object to put
        Throws:
        MathLinkException
      • put

        void put​(java.lang.Object obj,
                 java.lang.String[] heads)
          throws MathLinkException
        Sends an array object. Unlike put(Object), this method lets you specify the heads you want for each dimension.
             int[][] a = {{1,2},{3,4}};
             // The following are equivalent, sending to Mathematica the matrix: {{1,2},{3,4}}
             ml.put(a);
             ml.put(a, null);
             ml.put(a, new String[] {"List", "List"});
        Parameters:
        obj - must be an array
        heads - the heads at each dimension
        Throws:
        MathLinkException
      • setComplexClass

        boolean setComplexClass​(java.lang.Class cls)
        Specifies the class you want to map to Mathematica's Complex numbers.

        After calling setComplexClass(), you can use getComplex() to read an incoming Complex and create an instance of your class, and you can use put() to send objects of your class to Mathematica as Complex.

        To be suitable, your class must have a public constructor of the form MyComplex(double re, double im), and it must have two public methods double re() and double im().

        Parameters:
        cls - the class to map to Mathematica Complex numbers
        Returns:
        true, if the class is a suitable choice, false otherwise
        See Also:
        getComplexClass(), getComplex()
      • getComplexClass

        java.lang.Class getComplexClass()
        Gives the Java class that you have specified to map to Mathematica's Complex numbers.

        You specify the class you want using setComplexClass().

        Returns:
        the class, or null if no class has yet been specified
        See Also:
        setComplexClass(Class)
      • setYieldFunction

        boolean setYieldFunction​(java.lang.Class cls,
                                 java.lang.Object obj,
                                 java.lang.String methName)
        Sets the Java method you want called as a yield function.

        The method must be public and its signature must be (V)Z (e.g., public boolean foo()). You can pass null for cls if obj is provided. If the method is static, pass null as obj.

        Yield functions are an advanced topic, and are discussed in greater detail in the User Guide. Few users will need to use one.

        Parameters:
        cls - the class in which the method resides
        obj - the object on which the method should be invoked (use null if the method is static)
        methName - the name of the method to invoke
        Returns:
        true, if the specified method is suitable (i.e., could be found, and has the correct signature); false otherwise
      • addMessageHandler

        boolean addMessageHandler​(java.lang.Class cls,
                                  java.lang.Object obj,
                                  java.lang.String methName)
        Specifies the Java method you want called as a message handler.

        Do not confuse this type of message, used mainly for communicating requests to interrupt or abort a computation, with Mathematica warning and error messages, which are unrelated.

        The method you specify will be added to the set that are called whenever a MathLink message is received by your Java program. The method must be public and its signature must be (II)V (e.g., public void foo(int msgType, int ignore)). You can pass null for cls if obj is provided. If the method is static, pass null for obj. The first argument passed to your function when it is called is the integer code giving the message type (e.g., MLABORTMESSAGE, MLINTERRUPTMESSAGE, etc.) The second argument is undocumented and should be ignored.

        Do not attempt to use the link from within your message handler function.

        You can set more than one message handler, hence the name "addMessageHandler".

        Message handlers are an advanced technique. Few programmers will need to use one.

        Parameters:
        cls - the class in which the method resides
        obj - the object on which the method should be invoked (use null if the method is static)
        methName - the name of the method to invoke
        Returns:
        true, if the specified method is suitable (i.e., could be found, and has the correct signature); false otherwise
        See Also:
        removeMessageHandler(String)
      • removeMessageHandler

        boolean removeMessageHandler​(java.lang.String methName)
        Removes a message handler you previously set up with addMessageHandler.

        Do not confuse this type of message, used mainly for communicating requests to interrupt or abort a computation, with Mathematica warning and error messages, which are unrelated.

        Message handlers are an advanced topic, and are discussed in greater detail in the User Guide. Few users will need to use one.

        Parameters:
        methName - the name of the method to remove
        Returns:
        true, if the specified method was previously set as a message handler; false otherwise
        See Also:
        addMessageHandler(Class, Object, String)