Step By Step |
Now, you can finally get down to the business of writing the implementation for the native method in C.The function that you write must have the same function signature as the one you generated with
javah
into theHelloWorld.h
file in Step 3: Create the .h File. The function signature generated for theHelloWorld
class'sdisplayHelloWorld()
native method looks like this:Here's our implementation forextern void HelloWorld_displayHelloWorld(struct HHelloWorld *);HelloWorld_displayHelloWorld()
which can be found in the file namedHelloWorldImp.c
.As you can see, the implementation for#include <StubPreamble.h> #include "HelloWorld.h" #include <stdio.h> void HelloWorld_displayHelloWorld(struct HHelloWorld *this) { printf("Hello World!\n"); return; }HelloWorld_displayHelloWorld()
is straightforward: the function uses theprintf()
function to display the string "Hello World!" and then returns.This file includes 3 C header files:
StubPreamble.h
which provides enough information to the C code to interact with the Java runtime system. When writing native methods, you must always include this file in your C source files.- The
.h
file that you generated in Step 3: Create the .h File. This file contains the C structure that represents the Java class for which we are writing the native method and the function definition for the native method you are writing in this step.- The code snippet above also includes
stdio.h
because it uses theprintf()
function.
Step By Step |