Using py4j to send matrices to from Python to Java as int[][] arrays

孤街醉人 提交于 2019-12-04 18:05:20

I found a solution for this particular case that works; though it is not terribly elegant:

Py4j supports efficiently passing a Python bytearray object to Java as a byte[] array. I worked around the problem by modifying the original library and my Python code.

The new Java code:

public class MyClass {
   // ...
   public static MyObject create(int[][] matrix) {
      // ...
   }
   public static MyObject createFromPy4j(byte[] data) {
      java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(data);
      int n = buf.getInt(), m = buf.getInt();
      int[][] matrix = new int[n][m];
      for (int i = 0; i < n; ++i)
         for (int j = 0; j < m; ++j)
            matrix[i][j] = buf.getInt();
      return MyClass.create(matrix);
   }
}

The new Python code:

def create_java_object(numpy_matrix):
   header = array.array('i', list(numpy_matrix.shape))
   body = array.array('i', numpy_matrix.flatten().tolist());
   if sys.byteorder != 'big':
      header.byteswap()
      body.byteswap()
   buf = bytearray(header.tostring() + body.tostring())
   return java_instance.jvm.my.namespace.MyClass.createFromPy4j(buf)

This runs in a few seconds rather than a few minutes.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!