main
  • About
  • Civil Engineering
    • Interview questions
    • Bridge design
  • Google Cloud
    • Code samples
    • kafka
    • Cloud Run
    • persistent disks
    • Spinnaker
    • Assessment questions
    • IAM
    • Cloud Storage
    • VPC
    • Cost optimization
    • Compute Engine
    • App Engine
    • Cloud Vision
    • Spanner
    • Cloud SQL
    • Solutions
      • Static IP - WIP
      • Network performance
      • Building a VPN
      • Build a streaming app
      • ML train with taxi data
    • Dataproc
    • Dataprep
    • BigTable
    • Cloud Fusion
    • Data flow
    • CloudFront
    • APIGEE
    • BigQuery
    • Cloud logging
    • Pubsub
    • Identity Aware Proxy
    • Data center migration
    • Deployment Manager
    • Kubeflow
    • Kubernetes Engine
    • Istio
    • Read the following
    • Storage for cloud shell
    • kms
    • kpt
    • Hybrid cloud with Anthos
    • helm
    • Architecture
    • terraform
    • Network
    • Data studio
    • Actions
    • Jenkins
  • Data Processing
    • Data Lake
    • Data ingestion
    • Data Cleaning - Deduplication
    • Data Cleaning - Transformation
    • Data cleaning - rule definition
    • ETL
  • Machine Learning
    • Tensorflow
    • Tensorflow tips
    • Keras
    • Scikit-learn
    • Machine learning uses
    • Working with Pytorch
    • Federated learning
  • AWS cloud
    • Billing
    • Decrease volume size of EC2
    • Run CVE search engine
    • DataSync
    • EC2 spot instances
  • Java
    • Java
    • NIO
    • System Design
      • Zero trust framework
    • Collections
  • Azure
    • Enterprise Scale
    • API
    • Resource group
    • Create an sql database
  • UBUNTU
    • No Release file
    • STRATO blockchain
    • iperf
    • Rsync
    • curl
    • Shell
    • FAQ - git
  • PH test
    • Syllabus
    • Opportunities
    • Aptitude test
  • Development
    • Course creation
    • web.dev
    • docfx template
  • npm
  • Docker Desktop
  • Nginx
  • English rules
  • Confluent
  • sanity theme
  • Java Native Interface tutorial
  • Putty
  • Personal website host
  • Google search SEO
  • Reading a textbook
  • DFCC Progress
  • STORAGE
    • Untitled
  • Services Definition
    • Cloud VPN and routing
  • Microservices design and Architecture
    • Untitled
  • Hybrid network architecture
    • Untitled
  • Deployment
    • Untitled
  • Reliability
    • Untitled
  • Security
    • Untitled
  • Maintenance and Monitoring
    • Peering
  • Archive
    • parse dml to markdown
Powered by GitBook
On this page
  • 1 Write a Java class that uses C codes
  • 2 Compile Java program CraftJNI.java
  • 3 Implement C program
  • 4 Compile C program
  • Troubleshooting
  • Error 1: class file has wrong version
  • Error 2:
  • References

Was this helpful?

Java Native Interface tutorial

Create a Java class to use code in C

1 Write a Java class that uses C codes

CraftJNI.java
public class CraftJNI {
  static {
    System.loadLibrary("hello"); // Load native library hello.dll (windows)
                                 // or libhello.so (Unixes) at runtime.
                                 // This library contains a native method sayHello()

  }

  // Declare an instance native method sayHello() which receives no parameter
  // returns void
  private native void sayHello();

  // Test Driver
  public static void main(String[] args) {
    new CraftJNI().sayHello(); // Create an instance and invoke native method
  }
}

2 Compile Java program CraftJNI.java

javac -h . CraftJNI.java
CraftJNI.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class CraftJNI */

#ifndef _Included_CraftJNI
#define _Included_CraftJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     CraftJNI
 * Method:    sayHello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_CraftJNI_sayHello
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

To know more about the generated class file

javap -verbose CraftJNI.class

3 Implement C program

CraftJNI.c
#include <jni.h>   // Standard JDK provided header
#include <stdio.h> // Standard C IO header
#include <CraftJNI.h> // Generated header

JNIEXPORT void JNICALL Java_CraftJNI_sayHello(JNIEnv *env, jobject thisObj) {
  printf("I am in C code \n");
  return;
}

4 Compile C program

gcc -fPIC -I"." -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" \
   -shared -o libhello.so CraftJNI.c
> java -Djava.library.path=. CraftJNI
I am in C code

Troubleshooting

Error 1: class file has wrong version

> javah CraftJNI.class
Error: cannot access CraftJNI
  bad class file: ./CraftJNI.class
    class file has wrong version 55.0, should be 52.0

Reason: javah is not available with Java 11

> java -version
openjdk version "11.0.9.1" 2020-11-04
OpenJDK Runtime Environment (build 11.0.9.1+1-post-Debian-1deb10u2)
OpenJDK 64-Bit Server VM (build 11.0.9.1+1-post-Debian-1deb10u2, mixed mode, sharing)

> javac -version
javac 11.0.9.1

> javah -version
javah version "1.8.0_252"

> whereis java
java: /usr/bin/java /usr/share/java /usr/share/man/man1/java.1.gz

> ls /usr/share/man/man1 | grep java*
java.1.gz
javac.1.gz
javadoc.1.gz
javah.1.gz
javap.1.gz

Error 2:

> java -Djava.library.path=. CraftJNI
Exception in thread "main" java.lang.UnsatisfiedLinkError: no hello in java.library.path: [.]
        at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2670)
        at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:830)
        at java.base/java.lang.System.loadLibrary(System.java:1873)
        at CraftJNI.<clinit>(CraftJNI.java:4)

References

Previoussanity themeNextPutty

Last updated 4 years ago

Was this helpful?

JNI reference docs -

Some of the code is shamelessly copied from

https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/jniTOC.html
https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html