2

I am entering into Java world just now. I am facing problem when I try to compile sample program for Calling C from Java.

I wanted to try the sample code for JNI (Which is given in JNI.PDF from SUN-Micro).

The code is some thing like this:

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

I compiled using javac HelloWorld.java and after that got .H file for C program using "javah -jni HelloWorld"

Even my C code is also simple with :

#include <jni.h>
#include <stdio.h>
#include "HelloWorld.h"
JNIEXPORT void JNICALL
Java_HelloWorld_print(JNIEnv *env, jobject obj)
{
  printf("Hello World!\n");
  return;
}

I created .dll in Cygwin using "gcc -Wl,--add-stdcall-alias -shared -o HelloWorld.dll HelloWorld.c"

Even I used normal Linux method of Creating Shared Lib: "gcc -shared -Wl,-soname,libHelloWorld.so -o libHelloWorld.so HelloWorld.o"

But when I run java HelloWorld, it return Aborted!

Since i dont have much idea in Java, I am not sure where I going wrong.

I checked similar code present in few websites like: http://www.inonit.com/cygwin/jni/helloWorld/ but getting similar error.

3 Answers 3

4

I couldn't get JNI to work with Cygwin's g++ -- that induces a dependency on cygwin1.dll, which clashes with the JNI mechanism, causing a crash. The -mno-cygwin flag is no longer supported. But using /bin/x86_64-w64-mingw32-g++.exe fixed the problem for me.

Sign up to request clarification or add additional context in comments.

Comments

1

The InOnIt page uses -mno-cygwin. If you want Cygwin functionality, then you'll want http://elliotth.blogspot.com/2005/08/porting-jni-code-to-win32-with-cygwin.html. Terminator's moved since that was written. The crux of the source you'd want for a Cygwin-safe Java launcher is now at https://github.com/software-jessies-org/jessies/blob/master/salma-hayek/native/all/java-launcher/java-launcher.cpp.

Comments

0

Ensure that your native library is really loaded by adding a try/catch block around the System.loadLibrary() call to catch the UnsatifiedLinkError Exception if your library could not be found. If that doesn't work post your error, "it return aborted" isn't very helpful. Also, you defined the native print method with a void return type, yet you have a return statement. Either remove that or let the method actually return something.

2 Comments

Actually, the new HelloWorld().print() is necessary, as print() is not static.
You're right, I was thinking in Android where it isn't necessary since you have no main(). Edited my post above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.