Java passing an object, C++ calling the object

This example is an attempt to take the Java object out of the "center of the universe" position, and put a C++ object there instead. The next example does a better job to that end, but there are several things of interest here.

The original design created a Java object (line 30), and then explicitly passed it to the C function (lines 20, 28, and 57-58). This works, but it duplicates functionality that already exists. In a previous example, we saw that the Java object that calls a native method implicitly passes its "this pointer" as the second argument to the C function (line 52). As a result, passing the "this pointer" explicitly causes the same information to be passed twice - as the second argument, and, the third argument (lines 57 and 58).

The C function does nothing more than pass the JNI data structures to the C++ class's constructor (line 53). The C++ constructor is now controlling the application's flow of control. It has a "reference" to the Java object, and whenever it wants to present a JOptionPane window to the user, it calls the Java class's getInput() method which returns the string that was input by the user (lines 25 and 44).

Notice the Java method's signature at line 22, and the encoding of that signature at line 40.

[source: Horstmann98, pp599-600]