SJB
SJB

Reputation: 13

passing a 2d matrix from java to C++ file through jni

I have a 2d matrix in java say in a file MyClass.java in the method java_method() and I have declared a native method say c_method(). the matrix is float type like:

    float[][] pos_matrix;

of size 3by4 and I have initialized the matrix in java. Now I want to pass this matrix to my cpp file in the jni. How to do that?

Upvotes: 1

Views: 834

Answers (1)

Pavel Zdenek
Pavel Zdenek

Reputation: 7293

Two options:

  1. encode the matrix in 1D array of length 12, pass as float[]. Results in jfloatArray on native side. Cannot be used directly, read about Get/ReleaseFloatArrayElements
  2. wrap the Java matrix in a facade class with method float GetValueAt(int,int) (or similar) and access on native side by passing the instance (results in jobject on native side) and then calling that method (GetMethodID/CallFloatMethod)

Option 1 is simpler (less coding), option 2 is cleaner in "OO way" - separation of concerns. With option 1 you can practically modify the array when JVM is not looking.

Upvotes: 1

Related Questions