Professional Documents
Culture Documents
Mixed-Language
Development: Leveraging
Native Code from Java CON3408
Darryl Gove
Senior Principal Software Engineer
Outline
Overview of JNI
Mixed Java/native debugging
Mixed Java/native performance
Other solutions
Overview of JNI
Insert Picture Here
Using JNI
Insert Picture Here
class myApp
{
private native void go();
Native code
to be called
native code
Finding Libraries
Programmatically...
Current directory
Load library
Include JNI
header file
C linkage
Declaration of
native function
Define calling
convention
Pointer to
Java environment
Pointer to
calling object
Include header
file
#include "myApp.h"
Write native
code
Parameter Passing
Insert Picture Here
Function prototype
class Total
{
private native double sum(double[] array,int len);
void work()
{ double[] array=new double[2048];
for (int i=0; i<2048; i++) { array[i]=i*15.0; }
System.out.print("Total = ");
System.out.println( sum(array, 2048) );
}
public static void main(String[] args)
Function call
{ System.loadLibrary(Total);
new Total().work(); }
}
18Copyright 2012, Oracle and/or its affiliates. All rights reserved.
Function prototype
Parameter Passing
JNIEXPORT jdouble JNICALL Java_Total_sum
(JNIEnv * jenv, jobject job, jdoubleArray jd, jint len)
{
Copy Java array
double total = 0;
to native type
double* d =(*jenv)->GetDoubleArrayElements(jenv,jd,0);
for (int i=0; i<len; i++) { total += d[i]; }
(*jenv)->ReleaseDoubleArrayElements(jenv,jd,d,0);
return total;
}
Return result
Debugging Mix
Java/Native Applications
Performance Tuning
Mixed Java/Native
Applications
Gather profile
Function Profile
Native code
Java code
Java code
C code
Call where
time spent
C Source Code
Cost of converting
to native data
Line where
time spent
Cost of converting
data back to Java
Other Solutions
Insert Picture Here
Other Solutions
JNI
Built on JNI
Load library
class Len{
public interface LLib extends Library
{
LLib INSTANCE = (LLib)Native.loadLibrary("Length", LLib.class);
int textLen(String text);
}
Declare functions
void work()
{ System.out.println(LLib.INSTANCE.textLen(Hello)); }
public static void main(String[] args){new Len().work(); }
}
Call function
33Copyright 2012, Oracle and/or its affiliates. All rights reserved.
Function Profile
Concluding Remarks
Insert Picture Here
JNI
JNA/JNR