JNI error while calling a C subroutine - java

I want to call a C subroutine from Java. I'm using JNI. I have created the .java, .c, and .h files, and compiled a DLL. All the files are in the same folder. But when I run the program, it shows an unsatisfiedlinkError. Where am I going wrong...?
As I am learning JNI, the source code I used is the one from: http://www.ibm.com/developerworks/java/tutorials/j-jni/section2.html and things I have already tried:
Create a dll using Code::Blocks(ide) and GCC as the compiler
Create dll using GCC from command line (Ref. http://sig9.com/node/35 )
I am using Win7 32 bit, and I guess all the methods above generate 32-bit DLLs
All the solutions I found for creating a DLL (shared library) are for MS VC/VCPP and I don't have that on my machine right now.
Where is the problem? DLL files are being generated without any exception, but when I run the Java code, it throws the exception.
PS: If there is any theoretical examples that explains how JNI works and what actually it does, then kindly share the link...
The message or exception being thrown:
c:\myjava1>java Sample1
Exception in thread "main" java.lang.UnsatisfiedLinkError: Sample1.intMethod(I)I
at Sample1.intMethod(Native Method)
at Sample1.main(Sample1.java:11)
At the end of the day after creating dll file lots of times,I am pretty sure that there is possibly no issue with it ,something is wrong with the path ...I have changed the loadlibrary method with load method ,but still no luck,.....
as suggested by a MOD:
I have been discussing about this question on the post:JNI error while calling a C subroutine ,I am posting all the codes here as the comments have limited characters... Sample1.c
#include "jni.h"
#include"Sample_Sample1.h"
JNIEXPORT jint JNICALL Java_Sample_Sample1_test(JNIEnv *env, jobject obj){
return(1);
}
void main(){}
Sample1.java
package Sample;
public class Sample1
{
public native int test();
static{
System.loadLibrary("Sample1");
}
public static void main(String[] args)
{
Sample1 sample = new Sample1();
System.out.println(sample.test());
}
}
Sample_Sample1.h(generated using javah -jni command)
/* DO NOT EDIT THIS FILE - it is machine generated */
#include "jni.h"
/* Header for class Sample_Sample1 */
#ifndef _Included_Sample_Sample1
#define _Included_Sample_Sample1
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Sample_Sample1
* Method: test
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_Sample_Sample1_test
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Can anyone guide me where the issue is?In earlier post I mentioned that the code I am using is the one from tutorials ,but to simplyfy the things I have changed the codes ...While using **java Sample.Sample1" i am getting:
c:\myjava1>java Sample.Sample1
Exception in thread "main" java.lang.UnsatisfiedLinkError: Sample.Sample1.test()I
at Sample.Sample1.test(Native Method)
at Sample.Sample1.main(Sample1.java:12)

You need to have your library explicitly set on your path.
It may be the case that the flags you are using there aren't quite right. Try this:
gcc -Wall -D_JNI_IMPLEMENTATION_ -Wl,--kill-at \
-I[Java_HOME]/include -I[Java_HOME]/include/win32 \
-shared -o Sample1.dll Sample1.c
From MinGW GCC site.

Have you checked your DLL by calling it from a stub C++ application? Pay particular attention to the exact name (including capitalisation) of the method(s) you are calling.
The Javadoc for UnsatisfiedLinkError says "Thrown if the Java Virtual Machine cannot find an appropriate native-language definition of a method declared native." That probably means either that the name is misspelled or your DLL is not where the JVM is expecting to find it.

Finally solved the problem using System.load() method, System.loadLibrary() Still doesn't work for me...it keeps on giving the same exception, And the I think the issue was with the .dll Thanks to all of you who supported and responded...

After spending 2hrs and analysing the code. Problem is with .dll/.so compilation. Below command works for me:
g++ -dynamiclib HelloJni.cpp -I /usr/include/ -I /usr/lib/jvm/java-1.8.0-openjdk-amd64/include/ -I /usr/lib/jvm/java-1.8.0-openjdk-amd64/include/linux/ -shared -o libHelloJni.so
or
g++ -dynamiclib HelloJni.cpp -I /usr/include/ -I $JAVA_HOME/include/ -I $JAVA_HOME/include/linux/ -shared -o libHelloJni.so
Above command is for linux. In case of Windows, change
[Java_HOME]/include/linux/ ---> [Java_HOME]/include/win/
Mac:
$Java_HOME/include/linux/ ---> $Java_HOME/include/darwin/

Related

How to fix Java 15 JNI "UnsatisfiedLinkError: A dynamic link library (DLL) initialization routine failed"

I have found other posts of people having this exact error, but not one thus far has had a solution that worked for me. For reference, here are the things I have found:
https://community.oracle.com/tech/developers/discussion/2233828/jni-link-error-a-dynamic-link-library-dll-initialization-routine-failed
JNI UnsatisfiedLinkError: A dynamic link library (DLL) initialization routine failed
https://www.debugcn.com/en/article/5175409.html
https://coderanch.com/t/132356/engineering/java-lang-UnsatisfiedLinkError
Either their solution was not relevant to my particular scenario, or it did not fix the issue for me.
Everything is being compiled on the command line with a Windows 10 computer and using GCC (gcc-5.1.0-tdm64-1-c++) for compiling the C++ portions into a .dll, and JDK 15.0.1's javac tool. There are three relevant files here, one being the header file derived from the java file.
Main.java:
public class Main {
static {
System.load("C:\\Users\\17659\\Documents\\Programming\\C++ & Java - JNI Tests\\library.dll");
//System.loadLibrary("library");
}
public static void main(String[] args) {
new Main().outputText();
}
private native void outputText();
}
Main.h:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Main */
#ifndef _Included_Main
#define _Included_Main
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Main
* Method: outputText
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_Main_outputText
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Library.cpp:
#include <iostream>
#include "Main.h"
JNIEXPORT void JNICALL Java_Main_outputText(JNIEnv * a, jobject b)
{
std::cout << "testing";
}
They are contained all within the folder with the absolute path of C:\Users\17659\Documents\Programming\C++ & Java - JNI Tests. With a command prompt set to that as the current directory, I run the following commands in order:
g++ -c -o Library.o -I"C:\Users\17659\Documents\jdk-15.0.1\include" -I"C:\Users\17659\Documents\jdk-15.0.1\include\win32" Library.cpp
g++ -shared -o library.dll Library.o
javac Main.java
java Main
Despite the multiple things I have tried, I always get this same error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Users\17659\Documents\Programming\C++ & Java - JNI Tests\library.dll: A dynamic link library (DLL) initialization routine failed
at java.base/jdk.internal.loader.NativeLibraries.load(Native Method)
at java.base/jdk.internal.loader.NativeLibraries$NativeLibraryImpl.open(NativeLibraries.java:383)
at java.base/jdk.internal.loader.NativeLibraries.loadLibrary(NativeLibraries.java:227)
at java.base/jdk.internal.loader.NativeLibraries.loadLibrary(NativeLibraries.java:169)
at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2407)
at java.base/java.lang.Runtime.load0(Runtime.java:747)
at java.base/java.lang.System.load(System.java:1857)
at Main.<clinit>(Main.java:3)
I have used nm on the resulting .dll to make sure the name of the function is correct, and it does seem to be exactly as it should.
The entire point of this little project of mine is to figure out how JNI works, since I have a plan to write a small portion of a program in C++. The rest of the program though would work best in Java (for me). I do not know what I need to do to get this program to work, I have spent approximately 2 hours of googling and fiddling attempting to get it to function. This is on a 64-bit OS. How can I make this program run and print out the very little amount of text I would like it to print out?
Update: As per #JornVernee removing the line #include <iostream> and replacing the std::cout with a printf() to write to the console did actually work. So my question now becomes this: why does including a standard C++ header cause an error?
Well, #JornVernee effectively nailed the issue right on the head. It was a mismatch between the standard library I had for C++ and the one being loaded. I changed the version of GCC I was using to a more up-to-date version, recompiled the entire project, and the program works now.

JNI UnsatisfiedLinkError without wrong method names and with library path specified

I'm trying to work build my very first JNI application, following this tutorial: https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
Problem Summary: While running my application, I get an java.lang.UnsatisfiedLinkError error.
First I wrote the Class HelloJNI.java:
public class HelloJNI {
static {
System.loadLibrary("hello"); // Load native library at runtime
// hello.dll (Windows) or libhello.so (Unixes)
}
// Declare a native method sayHello() that receives nothing and returns void
private native void sayHello();
// Test Driver
public static void main(String[] args) {
new HelloJNI().sayHello(); // invoke the native method
}
}
This class I compiled with:
javac HelloJNI.java
Next I ran javah HelloJNI
This produced the following file HelloJNI.h:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloJNI */
#ifndef _Included_HelloJNI
#define _Included_HelloJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloJNI
* Method: sayHello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloJNI_sayHello
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Next I implemented HelloJNI.c:
#include <jni.h>
#include <stdio.h>
#include "HelloJNI.h"
// Implementation of native method sayHello() of HelloJNI class
JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) {
printf("Hello World!\n");
return;
}
Finally I compiled the c class:
gcc -I"/usr/lib/jvm/java-8-oracle/include" -I"/usr/lib/jvm/java-8-oracle/include/linux" -c -Wall -Werror -fpic HelloJNI.c
gcc -shared -o hello.so HelloJNI.o
This produces the files hello.so and HelloJNI.o. Next I try to run the code:
java -Djava.library.path=. HelloJNI
This produces the error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no hello in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1864)
at java.lang.Runtime.loadLibrary0(Runtime.java:870)
at java.lang.System.loadLibrary(System.java:1122)
at HelloJNI.(HelloJNI.java:3)
This seems to be the most common JNI error on the internet... My method names seem to be correct. I also ran:
nm hello.so | grep say
This gives me: 00000000000006b0 T Java_HelloJNI_sayHello which seems to be correct, i.e. the compiler didn't add additional characters. I simply ran out of ideas of things I could try. Any suggestions?
My OS: Linux Mint 13, GCC version 4.7.3, java version 1.8.0_60
==========UPDATE===============
When I replace System.loadLibrary("hello"); by System.load("/usr0/home/jkinable/workspace/javaIDEA/jnitest/hello.so"); my HelloWorld example works! However, I don't want to use an absolute path so I'm still looking for a way to use System.loadLibrary("hello"); instead? Any suggestions? I've also tried running on a different linux system, but I get the same issue.
It turns out that the problem is due to some naming convention on unix/linux platforms! When using:
System.loadLibrary("hello");
the file should not be named hello.so! Instead, the name should be libhello.so. On Windows, use hello.dll. I'm surprised that this issue is not mentioned in IBM's JNI tutorial: http://www.ibm.com/developerworks/java/tutorials/j-jni/j-jni.html
I'm not sure what the rationality behind this issue is. Why would you load a library "hello" which should be named libhello.so on your filesystem (instead of hello.so)?

Java Native Interface

I am quite new to JNI. Now I have a Question that, I have my own simple library in C. i have created both .so and .a library for my c library.
Generated libmymath.so Via following Command
gcc -shared -fPIC -o libmymath.so addnsub.o mulndiv.o
JNI.java
public class JNIPart
{
public native int addJNI(int a, int b);
public static void main(String args[])
{
JNIPart ja = new JNIPart();
int answer = ja.addJNI(10, 20);
System.out.println("Answer = "+ answer);
}
static
{
System.loadLibrary("mymath");
}
}
JNI.c
#include "JNIPart.h"
#include "stdio.h"
JNIEXPORT jint JNICALL Java_JNIPart_addJNI(JNIEnv *env, jobject thisObj, jint a, jint b)
{
return add(a, b);
}
JNI.h
#include "jni.h"
#include "addnsub.h"
#include "mulndiv.h"
JNIEXPORT jint JNICALL Java_JNIPart_addJNI(JNIEnv *env, jobject thisObj, jint a, jint b);
Note :- Function add() is part of my library.
Now When i am trying to compile JNI.c, It Works Fine with Following Command
gcc -c JNI.c -I="/home/axit/jdk1.7.0_67/include/"
Path of JDK include is for jni.h
Then I am Trying to Create the Shared Library Which should go to the System.loadLibrary() of Java
gcc -shared -fPIC -o libJNI JNI.o
As Mentioned earlier that, libJNI library will be go to the System.loadLibrary() of JNI.java
Question is :-
1) My libJNI Library Should Contain Both my own libmymath.so and JNI.o. Am i Right ?
2) When I am Trying to Generate the .so which is Combination of libmymath.so and JNI.o. It is giving error to as following
Command :-
gcc -shared -fPIC -o libJNI JNI.o libmymath.so
libJNI :- Library that should go in JNI.java, System.loadLibrary()
JNI.o :- Compiled JNI.c
libmymath.so :- my library that contains basic add, sub, mul, and division function
/usr/bin/ld: JNIPart.o: relocation R_X86_64_PC32 against undefined symbol `add' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Bad value
collect2: ld returned 1 exit status
If helper want more information, i'll be more specific and any help will be appreciated
Help me.
Thanks,
Axit Soni
Q: My libJNI Library Should Contain Both my own libmymath.so and JNI.o. Am i Right?
It sounds like your JNI.o calls code in libmymath.so. So yes, you need to specify libmylibmath.so in your link command, and you also need to make sure it's available at runtime.
Q: When I am Trying to Generate the .so which is Combination of libmymath.so and JNI.o. It is giving error undefined symbol 'add' can not be used when making a shared object; recompile with -fPIC
I would run "nm" against libmymath.so and make sure you actually have an "add". Perhaps you inadvertantly compiled one or more functions with C++, and the name is mangled?
It wouldn't hurt to do what the error says, and make sure everything is consistently built with "-fPIC".

How to solve "fatal: relocations remain against allocatable but non-writable sections" while using Java native interface?

I'm trying to call a C function inside a Java code.
I have this hava code.
public class JavaToC {
public native void helloC();
static {
System.loadLibrary("HelloWorld");
}
public static void main(String[] args) {
new JavaToC().helloC();
}
}
. I compiled it and then created header file. Then make the following HelloWorld.c file.
#include <stdio.h>
#include <jni.h>
#include "JavaToC.h"
JNIEXPORT void JNICALL Java_JavaToC_helloC(JNIEnv *env, jobject javaobj)
{
printf("Hello World: From C");
return;
}
I tried compiling this using "gcc -o libHelloWorld.so -shared -I/usr/java/include -I/usr/java/include/solaris HelloWorld.c -lc", but it gives the following result.
Text relocation remains referenced
against symbol offset in file
.rodata (section) 0x9 /var/tmp//cc.GaGrd.o
printf 0xe /var/tmp//cc.GaGrd.o
ld: fatal: relocations remain against allocatable but non-writable sections
collect2: ld returned 1 exit status
I'm working on Solaris 11, how can I solve this?
I cannot test this on a Solaris machine at the moment, but from http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/SPARC-Options.html
-mimpure-text suppresses the “relocations remain against allocatable but non-writable sections” linker error message. However, the
necessary relocations will trigger copy-on-write, and the shared
object is not actually shared across processes. Instead of using
-mimpure-text, you should compile all source code with -fpic or -fPIC.
the solution seems to be to add the -fpic option to generate position-independent code.

java c++ jni unsatisfied link error

I'm quite a newbie to Java JNI. I tried a helloCPP program but ran into problems. here's my code :
helloCPP.java;
public class helloCPP {
public native void hellocpp ();
static {
System.loadLibrary("helloCPP");
}
public static void main (String [] args) {
helloCPP hcpp=new helloCPP ();
hcpp.hellocpp ();
System.exit (0);
}
}
Then here's my hellocpp.cpp out of which I made helloCPP.dll ;
#include <iostream>
#include "helloCPP.h"
using namespace std ;
JNIEXPORT void JNICALL Java_helloCPP_hellocpp. (JNIEnv *env, jobject obj) {
cout <<"hello java, I'm c++\n";
}
int main (){};
I successfully built the helloCPP.dll. But when I try to run java helloCPP, I get this error:
Exception in thread "main"
java.lang.UnsatisfiedLinkError: helloCPP.hellocpp () V
at helloCPP.hellocpp(Native Method)
at helloCPP.main (helloCPP.java :8)
I'm doing all these stuff on a Windows 8 x86 operating system.
These are the commands I wrote:
javac helloCPP.java
javah helloCPP
g++ -c hellocpp.cpp
g++ -o helloCPP.dll hellocpp.cpp
This one generated the error:
java HelloCPP
Thanks in advance.
Most likely, the Java run-time cannot locate the DLL file. You have run the Java application with additional arguments (assuming the DLL file is in the current directory):
java -Djava.library.path=. HelloCPP
Update:
EJP has a good point. I think your link command isn't correct. The second g++ command should be something like:
g++ -o helloCPP.dll -shared hellocpp.o
There are two changes: hellocpp.o instead of hellocpp.cpp and more importantly the option -shared to indicate that you want to create a shared library and not an executable.
The exact options depend on your platform. As you haven't specified it, I can't tell you for sure.

Categories