Search code examples
javac++nativejna

Calling dll functions, through JNA, How to handle address passing through pointers in java?


Iam able to Call dlls functions through c++ , using these codes :

 extern "C" 
    {
    __declspec(dllimport) void _stdcall INPWAV
                 (char* Rad, int radLen,
                  float* wavlen);
    }
    .
    .
char rad[4];
float   Wavlen; 
    .
    .
        INPWAV(rad,4,&m_Wavlen);
    .
    .

But I wanna call it from java through JNA, I am wondering, How can I handle address passing, like I passed pointers in C++, as there are no pointers in java, and java donesn't support call by reference like c++ ?? Currently tried in java as :

public class CallDll {
    public interface callNative extends Library {
        public void INPWAV(char Rad, int radLen,float wavlen);
    }
    public static void main(String[] args) {
        callNative callNative1 = (callNative)Native.loadLibrary("PROCESSWAV", callNative.class);
          char rad[] = new char[4];
        float   Wavlen; 
        .
        .
        callNative1.INPWAV(rad,4,Wavlen);
    }
}

But getting errors.... as java doesn't accept call by reference, How can I can pass by reference here??? Thank you In advance !


Solution

  • Primitive arrays are passed as pointers to memory buffers.

    "Address of" semantics are provided by com.sun.jna.ptr.ByReference classes, which include FloatByReference (which support initialization of memory, if required).

    FloatByReference fref = new FloatByReference(5.0);
    // Equivalent to passing &float_value
    lib.callMyMethod(fref);
    float value = fref.getValue();
    

    EDIT

    ByReference implementations exist for all primitive types and generic pointers. You can always derive your own from the base abstract class if those don't fill your needs.