Search code examples
cjnaspss

JNA pointer to store file handle


I'm using JNA to use a .dll in Java.

The method i'm trying to use is this (in C):

int fH; /* file handle */
int error; /* error code */
error = spssOpenWrite("mydata.sav", &fH);

It creates a new file and stores the file handle in hFile and returns an error code. I'm not sure how to recreate that with JNA, i tried using the pointer-object like this:

Pointer fH = new Memory(4096);
int error = 0;
error = CLibrary.INSTANCE.spssOpenWrite("mydata.sav", fH);

But that doesn't change the value of fH.


Solution

  • The "value" of fH would be the same memory address that you originally defined. If you attempted to read that value, however, you should get the result, e.g., fH.getInt(0).

    However, allocating 4096 bytes to hold an integer is overkill. Why not just use the IntByReference class designed specifically for this purpose?

    int fH; /* file handle */
    int error; /* error code */
    IntByReference pFH = new IntByReference(); // allocates memory for the int
    error = CLibrary.INSTANCE.spssOpenWrite("mydata.sav", pFH);
    // TODO: test error value before proceeding
    fH = pFH.getValue();