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.
Start the JVM.
JPype is conveniently able to find the default JVM path:
jpype.startJVM(jpype.getDefaultJVMPath())
Print hello world.
Just because of tradition, let's print hello world:
jpype.java.lang.System.out.println("hello world")
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)
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...