Cover Page by Gary Cornell, Cay S. Horstmann

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required