2

I am using Linux (Ubuntu 12.10). I have tried this question on SO and a lot others on the web, but I am not able to solve my problem.

Here is the java file :

class HelloWorld
{
    public native void display();

    static
    {
        System.loadLibrary("HelloWorld");
    }   

    public static void main(String args[])
    {
        HelloWorld hw = new HelloWorld();
        hw.display();
    }
}

I compiled it using javac HelloWorld.java.

Then I created header file from .class file using javah -jni HelloWorld. I got this header file

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

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloWorld
 * Method:    display
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloWorld_display
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

After this I created the following C file :

#include <stdio.h>
#include "HelloWorld.h"

void display();

int main()
{
    display();
    return 0;
}

void display()
{
    printf("Hello World Naveen\n");
}

and compiled this using gcc -o libHelloWorld.so -fPIC -lc -shared -I/usr/lib/jvm/java-6-oracle/include/ -I/usr/lib/jvm/java-6-oracle/include/linux HelloWorld.c.

Then I did echo $LD_LIBRARY_PATH=.. But when I run java HelloWorld I am getting UnsatisfiedLinkError

Community
  • 1
  • 1
Naveen
  • 7,944
  • 12
  • 78
  • 165

2 Answers2

3

Your HelloWorld.c file should not contain main or display. Instead it should contain an implementation of the HelloWorld.display method. For example:

 #include "HelloWorld.h"
 #include <stdio.h>

 JNIEXPORT void JNICALL Java_HelloWorld_display (JNIEnv * env, jobject obj) {
     printf ("Hello World\n");
 }
Jack Whitham
  • 609
  • 4
  • 9
2

Your implementation of the native function in your C file must match the method signature that was generated.

Use

JNIEXPORT void JNICALL Java_HelloWorld_display(JNIEnv * env, jobject obj)
{
}

Not

void display()
{
}
James Wierzba
  • 16,176
  • 14
  • 79
  • 120