Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain a new Pointer in Java?

Tags:

java

c

pointers

jna

How can I call a method with this method signature in C from JNA?

int open_device(context *ctx, device **dev, int index);

The last two lines of the C method look like this:

*dev = pdev;
return 0;

That's the only use of dev in that method. That means that I have to pass a poiner to an empty pointer to the method, right? The method then fills the empty pointer with the address of a device object and I can pass the pointer to the device to other methods.

My question is: Is this the right way to do that? If it is, how do I allocate a new pointer from Java?


Based on the accepted answer, I did this:

Memory p = new Memory(Pointer.SIZE);
Memory p2 = new Memory(Pointer.SIZE);
p.setPointer(0, p2);
nativeLib.open_device(ctx, p, index);
return p2;
like image 780
thejh Avatar asked Nov 27 '10 22:11

thejh


People also ask

How do you get pointers in Java?

Java doesn't support pointer explicitly, But java uses pointer implicitly: Java use pointers for manipulations of references but these pointers are not available for outside use. Any operations implicitly done by the language are actually NOT visible.

How do you create a pointer variable in Java?

T *ptr; Thus, to declare iptr as a variable of type pointer-to-int, you would say: int *iptr; The notation "T *ptr" is meant to suggest that the value of *ptr is of type T.

What is replacement for pointers in Java?

Java uses the (safer) idea of references instead of pointers.

Does new in Java return a pointer?

The new operator does not create a separate pointer variable. It allocates a block of memory, calls constructors (if any), and returns to you the address of the block of memory.


1 Answers

It appears that the JNA Pointer class has setPointer and getPointer methods to allow for multiple indirection, and the Memory class to actually "allocate" native objects. So you should be able to do something like: (I'm just guessing from the JNA docs, I've not tested this)

Pointer pDev = new Memory(Pointer.SIZE); // allocate space to hold a pointer value
// pass pDev to open_device
Pointer dev = pDev.getPointer(0);        // retrieve pointer stored at pDev
like image 120
casablanca Avatar answered Oct 04 '22 08:10

casablanca