12.6.1. Instance Methods

As an example of calling a Java method from native code, let’s enhance the Printf

class and add a method that works similarly to the C function fprintf. That is, it should be able to print a string on an arbitrary PrintWriter object. Here is the definition of the method in Java:

class Printf3 {    public native static void fprint(PrintWriter out, String s, double x);    . . . }

We’ll first assemble the string to be printed into a String object str, as in the sprint method that we already implemented. Then, from the C function that implements the native method, we’ll call the print method of the PrintWriter class.

You can call any Java method from C by using the function call

(*env)->Call ...

Get Core Java® Volume II—Advanced Features, Ninth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.