Sending a NumPy array to JPype

In this recipe, we will start a JVM and send a NumPy array to it. We will print the received array using standard Java calls. Obviously, you will need to have Java installed.

How to do it...

First, we need to start the JVM from JPype.

  1. Start the JVM.

    JPype is conveniently able to find the default JVM path:

    jpype.startJVM(jpype.getDefaultJVMPath())
  2. Print hello world.

    Just because of tradition, let's print hello world:

    jpype.java.lang.System.out.println("hello world")
  3. Send a NumPy array.

    Create a NumPy array, convert it to a Python list, and pass it to JPype. Now, it's trivial to print the array elements:

    values = numpy.arange(7)
    java_array = jpype.JArray(jpype.JDouble, 1)(values.tolist())
    
    for item in java_array:
        jpype.java.lang.System.out.println(item)
  4. Shutdown the JVM.

    After we are done, we will shutdown the JVM:

    jpype.shutdownJVM()

    Only one JVM can run at a time in JPype. If we forget to shutdown the JVM, it could lead to unexpected errors. The program output is as follows:

    hello world
    0.0
    1.0
    2.0
    3.0
    4.0
    5.0
    6.0
    JVM activity report     :
      classes loaded       : 31
    JVM has been shutdown
    

The complete code for this recipe is as follows:

import jpype
import numpy

#1. Start the JVM
jpype.startJVM(jpype.getDefaultJVMPath())

#2. Print hello world
jpype.java.lang.System.out.println("hello world")

#3. Send a NumPy array
values = numpy.arange(7)
java_array = jpype.JArray(jpype.JDouble, 1)(values.tolist())

for item in java_array:
   jpype.java.lang.System.out.println(item)

#4. Shutdown the JVM
jpype.shutdownJVM()

How it works...

JPype allows us to start up and shut down a Java Virtual Machine. It provides wrappers for standard Java API calls. As we saw in this example, we can pass Python lists to be transformed to Java arrays by the JArray wrapper. JPype uses the Java Native Interface (JNI), which is a bridge between native C code and Java. Unfortunately, using JNI hurts performance, so you have to be mindful of that fact.

See also

  • Installing JPype in this chapter
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset