简体   繁体   English

使用 Py4J 将双精度数组从 Java 传递到 Python

[英]Passing an Array of doubles from Java to Python using Py4J

I want to send arrays of double s (or float s) from Java to Python using Py4J.我想使用 Py4J 将 arrays 的double s(或float s)从 Java 发送到 Python。 But it can't seem to be working.但它似乎无法正常工作。 Here is my MWE on the Java side.这是我在 Java 端的 MWE。

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:启动网关服务器后,我从Python访问object:

>>> 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 double s or float s from Java to Python?如何正确地将double s 或float s 的数组从 Java 发送到 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).我的用例很简单:我只需要从 Java 接收值。不需要能够修改数组(Python 端的list )。 Hence if receiving it as a tuple is possible and easier, that's even better.因此,如果将它作为tuple接收是可能且更容易的,那就更好了。

Thanks!谢谢!

My current solution is to utilize the List in Java, as follows:我目前的解决方案是利用Java中的List ,如下:

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:它在 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM