0

I want to send arrays of doubles (or floats) from Java to Python using Py4J. But it can't seem to be working. Here is my MWE on the Java side.

The primary program
public class TheExample {
    
    private double sq[];

    public double twoTimes(double element) {
        return 2*element ;
    }
    
    public double[] squares(double x, double y) {
        sq = new double[2];
        sq[0] = x*x ;
        sq[1] = y*y ;
        return sq ;
    }

}
The entry point program
import py4j.GatewayServer;

public class TheExampleEntryPoint {

    private TheExample thex;

    public TheExampleEntryPoint() {
      thex = new TheExample();
    }

    public TheExample getThex() {
        return thex;
    }

    public static void main(String[] args) {
        GatewayServer gatewayServer = new GatewayServer(new TheExampleEntryPoint());
        gatewayServer.start();
        System.out.println("Gateway Server Started");
    }

}

After starting the Gateway Server, I accessed the object from Python:

>>> from py4j.java_gateway import JavaGateway
>>> gateway = JavaGateway()
>>> thex = gateway.entry_point.getThex()
>>> thex.twoTimes(9.0)
18.0
>>> thex.squares(2.0, 3.0)
JavaObject id=o1
>>> ### ??? The surprise

How to properly send an Array of doubles or floats from Java to Python?

My use case is simple: I need only to receive the values from Java. Not necessary to be able to modify the array (the list on the Python side). Hence if receiving it as a tuple is possible and easier, that's even better.

Thanks!

fajar
  • 161
  • 7

1 Answers1

0

My current solution is to utilize the List in Java, as follows:

The primary program

import java.util.List;
import java.util.ArrayList;

public class TheExample {
    
    public double twoTimes(double element) {
        return 2*element ;
    }
    
    public List<Double> squares(double x, double y) {
        List<Double> sq = new ArrayList<Double>();
        sq.add(x*x) ;
        sq.add(y*y) ;
        return sq ;
    }

}

And it works as expected in the Python side:

>>> from py4j.java_gateway import JavaGateway
>>> gateway = JavaGateway()
>>> thex = gateway.entry_point.getThex()
>>> thex.twoTimes(9.0)
18.0
>>> thex.squares(2.0, 3.0)
[4.0, 9.0]
fajar
  • 161
  • 7