Search code examples
javajna

JNA passing reference of array into native DLL


The function in the dll is:

int getInfo (
  unsigned int Index,
  unsigned int* Mask,
  unsigned int* Serial,
  unsigned __int64* licInfo);

It is important that licInfo is an array with 4 elements.

In Java the method is declared like this:

int getInfo(int Index, IntByReference Mask, IntByReference Serial, Memory licInfo);

the method call:

int Index = 0;
IntByReference Mask = null;
IntByReference Serial = null;
Memory LicInfo = new Memory(256);    
int status = dll.INSTANCE.getInfo(Index, Mask, Serial, licInfo);

The dll returns an error code that says the parameters are wrong. I am pretty sure the mistake is the last parameter. I also tried passing an long array directly or passing an Pointer without success.


Solution

  • The function mapping itself looks sane, although I would replace Memory with Pointer in the mapping. As Memory extends Pointer you can still initialize and pass the value as you do now.

    Without the API documentation specifying what it expects for arguments, I must make some educated guesses as to the problem. The native function expects an int and 3 pointers to information, the last of which you've stated is an array of long. What is expected in the first two?

    The problem is most likely the null values being passed for the Mask and Serial pointers. Unless the API specifically says null is allowed there, these should most likely be initialized with new IntByReference() to allocate native-side memory for an int that can be populated on the native side.

    While over-allocating memory for the long[4] shouldn't specifically cause the error, you've allocated 256 bytes for a 256 bit array. Allocating new Memory(32) should suffice.