How to obtain a new Pointer in Java?

前端 未结 3 1814
闹比i
闹比i 2021-01-18 00:07

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 line

相关标签:
3条回答
  • 2021-01-18 00:15

    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
    
    0 讨论(0)
  • 2021-01-18 00:21

    Even better answer. You may want to allocate (malloc etc) depending upon Java String length. Example below is unit test from JNA project.

    public void testGetSetStringWithDefaultEncoding() throws Exception {
        final String ENCODING = Native.DEFAULT_ENCODING;
        String VALUE = getName();
        int size = VALUE.getBytes(ENCODING).length+1;
        Memory m = new Memory(size);
        m.setString(0, VALUE);
        assertEquals("Wrong decoded value", VALUE, m.getString(0));
    }
    
    0 讨论(0)
  • 2021-01-18 00:22

    There are no pointers in Java, only references.

    You cannot reassign a reference when you pass them to methods, because you pass them by value. Everything is passed by value in Java.

    You can rewrite this method to instantiate a new instance of the device and return that instead of an int.

    0 讨论(0)
提交回复
热议问题