Search code examples
javapointersdllnativejna

JNA how call a method from java in an Pointer received from dll?


I have a method in the dll which returns a pointer to an object

C code

basic_hash* getAlgorithmInstance( int algorithm )

object has the following methods:

void reset ();
void hash (const byte* data, uint64 size, vector_byte& hash).

how can I call the methods of this object?

I have an implementation which returns a pointer

java code

public interface LIB extends Library {
        LIB INSTANCE = (LIB ) Native.loadLibrary(
                (Platform.isWindows() ? "LIB " : "linuxLIB"), LIB.class);
        Pointer getAlgorithmInstance(int i);
    }

    public static void main(String[] args) {
        try {
            LIB lib = LIB.INSTANCE;
            Pointer pointer = lib.getAlgorithmInstance(0);
            //pointer.reset(); //TODO how call?
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

Solution

  • You need to declare callbacks for each function pointer. Here's an example for "reset".

    public class BasicHash extends Structure {
        public interface Reset extends Callback {
            public void invoke();
        }
        public Reset reset;
        public BasicHash() { }
        public BasicHash(Pointer p) { super(p); read(); }
    }
    
    BasicHash hash = mylib.getAlgorithmInstance(0);
    hash.reset.invoke();