Search code examples
javapointersjna

How to write data in memory using JNA Pointer?


I have a Pointer to a memory like:

Pointer pData = new Memory(65536);

and I need to get the pointer of that memory starting from position 8 because I want to send that partof the memory (from 8 to the 65535) to a native C API.

I used:

pData8 = pData.getPointer(8);

to obtain the pointer starting from position 8 then I tried to write something to pData8 using:

pData8.setInt(0xAAAA);

just to verify that I was writing in the right position but I get Error: Invalid memory access.

How can I obtain a valid pointer to a part of the memory and be able to write on it?

below the details:

    80 Pointer pM = new Memory(65536);
    81 Pointer p = pM.getPointer(4);
    82 pM.setInt(0, 0xFFFF);
    83 p.setInt(0, 0xBBBB);

Exception in thread "main" java.lang.Error: Invalid memory access
at com.sun.jna.Native.setInt(Native Method)
at com.sun.jna.Pointer.setInt(Pointer.java:1124)
at it.caen.dig.Demo.main(Demo.java:83)

Solution

  • It looks like you're using the wrong API. getPointer returns the value found at that offset as a pointer (which probably points nowhere). If you want to get a pointer to that offset, use share:

    Provide a view of this memory using the given offset to calculate a new base address.

    Pointer pM = new Memory(65536);
    Pointer p = pM.share(4);
    pM.setInt(0, 0xFFFF);
    p.setInt(0, 0xBBBB);