Question

I'm making an interface to a DLL library, so i can use it with Java. I need my native function to modify the value of a jlong parameter. Like the parameter was passed by reference. My Java method must have the exact parameters as the native function MPUSBWrite shown down here.

Example of actual not working code: The MPUSBWrite gets its 4th parameter as reference and modify itrs value. I always get 0 when i read the pLength passed variable.

Java:

public static native boolean Write(long handle, byte[] pData, int dwLen, long pLength, int dwMilliseconds);

Native C++:

JNIEXPORT jboolean JNICALL Java_jPicUsb_iface_Write
(JNIEnv *env, jclass jc, jlong handle, jbyteArray pData, jint dwLen, jlong pLength, jint dwMilliseconds) {
    jniByteArray b(env, pData);
    DWORD res = MPUSBWrite((HANDLE)handle,b.getBytes(),dwLen,(PDWORD)pLength,dwMilliseconds);
    if (res) {
        return JNI_TRUE;
    } else {
        return JNI_FALSE;
    }
}

Is there a way my C++ code modify the value of the pLength variable by reference?

Was it helpful?

Solution

No.

Your best option, if you truly need to do this, is to define your fourth parameter as a long[], and have your JNI code update the array element.

Actually, your best option would be to consider why you can't return the long from the method.

OTHER TIPS

SWIG supports this functionality.

With SWIG you can update Java parameter values like pointers in C++. This is working for Object parameters very fine. You can put a Long object in to get it work.

With Swig you can write a layer between java and C++ where you can put the pointer value after a function call into the Java object. Swig also generates the Java classes, you have to us to call the C++ functions. When the C++ function contains another C++ class as parameter, Swig generates this C++ class as Java object with getter,setter and all C++ functions you want to call.

For this functionality Swig has a special language you have to write in a VisualStudio project. but all this is described in the Swig Manual

SWIG is a software development tool that connects programs written in C and C++ with a variety of high-level programming languages. SWIG is used with different types of languages including common scripting languages such as Perl, PHP, Python, Tcl and Ruby. The list of supported languages also includes non-scripting languages such as C#, Common Lisp (CLISP, Allegro CL, CFFI, UFFI), Java, Lua, Modula-3, OCAML, Octave and R.

This is not a JNI issue. The function is called by value, there is no way to modify that. Pass in an object or an array, so you can have the reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top