JNI Linking

Started by
1 comment, last by the_edd 12 years, 2 months ago
Pretty much taken straight out of the wikipedia Java Native Interface page, I made 3 files:

HelloWorld.java:

class HelloWorld
{
private native void print();
public static void main(String[] args) {
//new HelloWorld().print();
}
static {
System.loadLibrary("HelloWorld");
}
}


HelloWorld.h

/* 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: print
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloWorld_print
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif


libHelloWorld.c

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

JNIEXPORT void JNICALL
Java_HelloWorld_print(JNIEnv *env, jobject obj)
{
printf("Hello World!\n");
return;
}


The java code compiled fine, this line gave me no errors (I am assuming this is the correct usage)


gcc -I C:\glassfish3\jdk\bin\include -shared libHelloWorld.c -o libHelloWorld.so

But then I try to run the java code and I get this:

Exception in Thread "main" java.lang.UnsatifiedLinkError: no HelloWorld in java.library.path

So I replaced, in the java code, the System.loadLibrary parameter with HelloWorld.h, HelloWorld.c, libHelloWorld.c, and libHelloWorld.so. Each gave me that UnsatisfiedLinkError.

My directory looks like this:

a.exe (I'd also like to know how to control the name of the resulting .exe from running c++.exe on a c++ file)
libHelloWorld.c
HelloWorld.class
HelloWorld.h.gch (No idea what that is, or how it got there)
HelloWorld.h
HelloWorld.java
libHelloWorld.so
Compiler.bat

The files are all there in that directory. jni.h is in C:\glassfish3\jdk\bin\include, so where is this UnsatifiedLinkError coming from? Thanks in advance!
A penny for my thoughts? Do you think I have only half a brain?

Not-so-proud owner of blog: http://agathokakologicalartolater.wordpress.com/
Advertisement
The VM does not automatically search the working directory or environment directories. You have to specify the the path(s) to native libraries.
It should work relative to the working directory though, so try running you java app using:

java -Djava.library.path=./ HelloWorld
You should also give your dynamic library a ".dll" extension on Windows. You might also need to remove the "lib" prefix, but I don't think that's necessary.

This topic is closed to new replies.

Advertisement