我想使用Py4J从Java发送double
s(或float
s)的数组到Python。但这似乎不起作用。这是我在Java方面的MWE。
主程序
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 ;
}
}
入口点程序
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");
}
}
启动网关服务器后,我从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
如何正确地发送一个数组的double
s或float
s从Java到Python?
我的用例很简单:我只需要从Java接收值。不需要能够修改数组(Python端的list
)。因此,如果将其作为tuple
接收是可能的并且更容易,那就更好了。
谢谢!
我目前的解决方案是利用Java中的List
,如下所示:
主程序
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 ;
}
}
它在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)
[4.0, 9.0]