Search code examples
javamemorydlljna

JNA 4.2.1 call dll method without params


i use jna 4.2.1 I have a method in the dll which returns a pointer to an object (C++)

basic_hash* getAlgorithmInstance( int algorithm )

basic_hash has the following methods (C++):

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

i have interface (java)

public interface HAL extends Library {
  HAL INSTANCE = (HAL) Native.loadLibrary(
    (Platform.isWindows() ? "HAL" : "libHAL"), HAL.class);
  BasicHash getAlgorithmInstance(int i);
}
public static class BasicHash extends Structure {
  public BasicHash() {}
  public BasicHash(Pointer p) {
    super(p);
    read();
  }
  @Override
  protected List getFieldOrder() {
    return Arrays.asList(new String[] { "reset", "hash", "partial", "finalize" });
  }
  public interface Reset extends Callback { public void invoke();}
  public Reset reset;
  public interface Hash extends Callback {public void invoke(byte[] data, long size, byte[] hash);}
  public Hash hash;
  public interface Partial extends Callback {public void invoke(Pointer data, long size);}
  public Partial partial;
  public interface Finalize extends Callback {public void invoke(byte[] hash);}
  public Finalize finalize;
}

and when I use the method without parameters in main()

HAL lib = HAL.INSTANCE;
BasicHash b = lib.getAlgorithmInstance(0);
b.reset.invoke();

I get an error:

Exception in thread "main" java.lang.Error: Invalid memory access
  at com.sun.jna.Native.invokeVoid(Native Method)
  at com.sun.jna.Function.invoke(Function.java:374)
  at com.sun.jna.Function.invoke(Function.java:323)
  at com.sun.jna.Function.invoke(Function.java:275)
  at com.sun.jna.CallbackReference$NativeFunctionHandler.invoke(CallbackReference.java:646)
  at com.sun.proxy.$Proxy1.invoke(Unknown Source)
  at net.erver.ItServer.main(ItServer.java:79)

Why did I receive this error if the method resets the variables within the library? the method itself fulfills without problems (according to developers dll)

EDIT: vector_byte has definition:

typedef unsigned char byte;
typedef std::vector< byte > vector_byte

and basic_hash has definition:

namespace HAL { namespace algorithms {
  HAL_HASH_API enum class State : byte {
    Normal,
    Finished,
  };
  class HAL_HASH_API basic_hash 
  {
    public:
    virtual ~basic_hash() {}
    virtual void reset() = 0;
    virtual void partial( const byte*, uint64 ) = 0;
    virtual void finalize( vector_byte& ) = 0;
    virtual void hash( const byte*, uint64, vector_byte& ) = 0;

    bool isFinished() {
      return ( _state == State::Finished ? true : false );
    }
    protected:
      State _state;
  };
}
}

Solution

  • You need to use plain vanilla struct to pass data between JNA and your library. A C++ class (including a vector template) has a much different memory layout than does a simple C struct.