Prabhu Konchada
Prabhu Konchada

Reputation: 548

How to pass a structure as an argument to java function or return to java from jni

I have two questions Say I have some structure in jni say

struct X
{
    Type_A x;
    Type_B y;
}

Now how do I?

  1. Pass this structure as an argument to a java call back function
  2. How do I return this structure to a Java function.

If possible, please give an example.

Upvotes: 5

Views: 2869

Answers (4)

technomage
technomage

Reputation: 10069

Java Native Access handles the details automatically (in addition to avoiding the native compilation step entirely).

public class MyStructure extends com.sun.jna.Structure {
    public int x;
    public int y;
}

It also supports nested types, so you can have structures, pointers, or even unions as fields within the structure.

Upvotes: 2

18446744073709551615
18446744073709551615

Reputation: 16832

If you pass a data structure to Java, this must be a Java object. You can either create it on the JNI side, or fill in a parameter object passed to JNI by Java. (E.g. Java can create a new byte[4096] and pass it to a JNI function to store the result there.)

BUT sometimes you want Java to store pointers to native structures. You cast such pointer to an int/long and pass it to Java. No Java garbage collector would free such memory, you have to do that explicitly (as in C). In addition, you will need to call a JNI function to free such memory. You could play with finalize(), but I'd recommend explicit deallocation at predictable times from predictable threads(!).

Upvotes: 1

Prabhu Konchada
Prabhu Konchada

Reputation: 548

I think I finally figured this out there are two approaches

  1. Create an object in java --> send it to the native code --> fill it
  2. Create an object in the native code --> return it back

I have done it in both these approaches and it works like a charm If there is a better approach please do let me know....

What worries me is how does garbage collection function for an object created in the native side ???? If you have an answer please do comment below

And if anyone is facing a similar problem comment below so that I can post the code...

Upvotes: 1

You should use a object to represent the struct. the object could be something like this:

public class Struct {

private Type_A x;
private Type_B y;


public Struct(Type_A x, Type_B y) {
    this.x = x;
    this.y = y;
}


public Type_A getX() {
    return x;
}

public void setX(Type_A x) {
    this.x = x;
}

public Type_B getY() {
    return y;
}

public void setY(Type_B y) {
    this.y = y;
}

}

To use, you can invoque a function like this:

myFunction(new Struct(x,y));

and the function return the object like this:

public Struct myFunction(Struct struct){

   ....
   return struct;
} 

Hope it helps you!!

Upvotes: 0

Related Questions