How to obtain a new Pointer in Java?

感情迁移 提交于 2019-12-01 16:12:51
casablanca

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

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.

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