Search code examples
javadlljna

How to simulate objectpointers


I hava a facade object for a dll that i cant modify using jna. The dll keeps internal states and should always be the same instance. The facade object keeps state aswell.

If I understand correctly, if i change a non-primitive of an object, that change will not traverse back to the caller since the internal pointer to that non-primitive might have changed.

Is there a better way then passing around a wrapperobject to keep all changes? eg.:

public class Facade

{
    private final Dll dll;
    public Facade(int foo, int bar)
    {
        //init the Facade
        this.dll = new Dll();
    }
    int foo(int bar)
    {}
    // more methods
}

public class Wrapper
{
    public final Facade facade;

    public Wrapper(Facade facade)
    {
        this.facade = facade;
    }
}

public static class App
{
    public static int main(String[] args)
    {
        Facade fac = new Facade(0,0);
        Wrapper pointerSim = new Wrapper(fac);

        methodA(pointerSim);
        methodB(pointerSim);
    }
}

With the goal of pointerSim reflecting the changes after methodA and B to Member classes and byte arrays.

Or is my pretense false?


Solution

  • You can pass around native objects using a simple Pointer. That class has a number of accessor methods to read offsets into memory from the base pointer.

    If you want type safety around a specific class of pointers, you can make your own pointer type with

    public class Facade extends PointerType { 
        public Facade() { }
        public Facade(Pointer p) { }
    }