Search code examples
javapointersjna

Accessing JNA Pointer's peer value


I'm using JNA. The Pointer class represents a native pointer. It seems quite common to access the pointer's address which seems to be the peer member variable. However, they made sure you can't query it. Why? What's the recommended way to getting it if you want to work with it?

I wrote the following "hack":

public static long getBaseAddress(Pointer pointer)
{
    String stringPointer = pointer.toString();
    String[] splitStringPointer = stringPointer.split("@");
    int expectedSplitLength = 2;

    if (splitStringPointer.length != expectedSplitLength)
    {
        throw new IllegalStateException("Expected a length of "
                + expectedSplitLength + " but got " + splitStringPointer.length);
    }

    String hexadecimalAddress = splitStringPointer[1].substring("0x".length());
    return parseLong(hexadecimalAddress, 16);
}

But isn't there a proper way other than abusing the toString() method for grabbing the address?

I want to use Reflection even less than the approach above since it is also brittle.


Solution

  • While subclassing (as in technomage's answer) works, it's unnecessary. Pointer.nativeValue(p) will give you p's peer.

    And as in my comment to the other answer, "Don't use this unless you know what you're doing." It's generally not needed for anything inside JNA. Only if you actually need the memory address for some other purpose is the peer value truly relevant. You can iterate an offset from 0 to accomplish idioms like the code sample in the link you posted in your comment there.

    The Pointer's getters all take an offset argument, and you can also simply return a pointer to an offset from the original peer value using share().