JNI trouble

Hi,
Below is my attempt at calling a C++ function (DllLoader.processQuery), which in turn calls a Java function (getParameter) of the calling class. The execution reaches the C++ function, the trouble is that the jmethodID I get is NULL. Can you tell me where I went wrong?
Thanks for your help,
Miguel
// java code
public class RouteServlet extends HttpServlet {
  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    String respStr = DllLoader.processQuery();
  public String getParameter(String name) {
    return request.getParameter(name);
class DllLoader {
  public static native String processQuery();
// C++ code
JNIEXPORT jstring JNICALL Java_DllLoader_processQuery
  (JNIEnv *env, jclass cl) {
  jmethodID id_getParameter = env->GetMethodID(cl,"getParameter","(Ljava/lang/String;)Ljava/lang/String;");

Daniel,
Thank you so much for your help. It definitely put me on the right track. However I'm not at the end of the trip yet. You will notice below that I try to call the Java method using the objct id I got with your help. The trouble is that I get a null value for jvalueObj. If you are kind enough to let me know what is wrong this time, perhaps you can take a look at the rest of the code where I attempt to cast the object I will hopefully get to a jstring, and then get the character string.
Thanks again,
Miguel
public class RouteServlet extends HttpServlet {
  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    String respStr = DllLoader.processQuery(this);
  public String getParameter(String name) {
    return request.getParameter(name);
class DllLoader {
  public static native String processQuery(RouteServlet obj);
JNIEXPORT jstring JNICALL Java_DllLoader_processQuery
  (JNIEnv *env, jclass cl, jobject rtServ) {
jclass rtServ_cl=  env->FindClass("RouteServlet");
  jmethodID id_getParameter = env->GetMethodID(rtServ_cl,"getParameter","(Ljava/lang/String;)Ljava/lang/String;");
  jstring jstrParam = env->NewStringUTF("cmd");
  jobject jvalueObj = env->CallObjectMethod(rtServ,id_getParameter,jstrParam);
  jstring jvalueStr = (jstring)jvalueObj;
  jsize lengthStr = env->GetStringUTFLength(jvalueStr);
  const jbyte *bytesStr = (const signed char *)env->GetStringUTFChars(jvalueStr,JNI_FALSE);

Similar Messages

  • Trouble using JNI

    Hi everyone
    I have a problem, with a class which has native functions(JNI).
    The application I�m developing, uses thread�s. At the beginning before thread starts his job, application calls a native function without problem. But when another thread calls another native function(same class) generates the next error :
    java.lang.UnsatisfiedLinkError: estarEnEjecucion
    at MemoriaCompartida.estarEnEjecucion(Native Method)
    at MemoriaCompartida.estarEnEjecucion(MemoriaCompartida.java:72)
    at Censor.timerIntervalo(Censor.java:82)
    at Timer.run(Timer.java:225)
    at java.lang.Thread.run(Thread.java:534)
    What seems to be the problem???
    Thanks a lot for your help

    First of all,
    when I use JNI, I like to put the System.loadLibrary() on a static method in the first class I know will be loaded.
    like this:
    static {
        System.loadLibrary("Name");
    }So I know that Library was succesfuly loaded.
    Anyway, I bet that your library do NOT have the method you are trying to access, or maybe is missing parameters!
    Check it!
    If I didn't helped, please put the call of the methods in the java file and the library, if you can.
    Cya...
    Message was edited by:
    pbulgarelli
    Message was edited by:
    pbulgarelli

  • Trouble returning String from JNI method

    I'm a JNI newbie who is going through the SUN online book on JNI and have put together the 2nd program example (right after "helloworld"), but it is not working right. It is supposed to prompt you for a string, then returns the string that you type in. Right now it compiles without error, but it returns only the first word that I type, not the whole sentence. What am I doing wrong?
    Here's the code:
    Prompt.java
    package petes.JNI;
    public class Prompt
        private native String getLine(String prompt);
        static
            System.loadLibrary("petes_JNI_Prompt");
        public static void main(String[] args)
            Prompt p = new Prompt();
            String input = p.getLine("Type a line: ");
            System.out.println("User typed: " + input);
    }petes_JNI_Prompt.h
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class petes_JNI_Prompt */
    #ifndef _Included_petes_JNI_Prompt
    #define _Included_petes_JNI_Prompt
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class:     petes_JNI_Prompt
    * Method:    getLine
    * Signature: (Ljava/lang/String;)Ljava/lang/String;
    JNIEXPORT jstring JNICALL Java_petes_JNI_Prompt_getLine
      (JNIEnv *, jobject, jstring);
    #ifdef __cplusplus
    #endif
    #endifpetes_JNI_Prompt.c
    #include <jni.h>
    #include <stdio.h>
    #include "petes_JNI_Prompt.h"
    JNIEXPORT jstring JNICALL Java_petes_JNI_Prompt_getLine
      (JNIEnv *env, jobject this, jstring prompt)
         char buf[128];
         const jbyte *str;
         str = (*env)->GetStringUTFChars(env, prompt, NULL);
         if (str == NULL)
              return NULL;  /*  OutOfMemoryError already thrown */
         printf("%s", str);
         (*env)->ReleaseStringUTFChars(env, prompt, str);
         // assume here that user will ty pe in 127 or less characters
         scanf("%s", buf);
         return (*env)->NewStringUTF(env, buf);
    }Thanks in advance!
    /Pete

    OK, I have something that works now by substituting fgets for scanf. I have two other questions:
    1) Do I need to free the memory created in buf? Will it allocate memory every time the method is run? Or will it allocate only once on creation, and so is no big deal?
    2) A minor question: When I run this program in eclipse, the prompt string is displayed in the console only after the input string is entered and displayed. It works fine when I run it from the command line however. I have a feeling that this is a problem with how Eclipse deals with native methods and perhaps nothing I can fix. Any thoughts?
    Thanks
    Pete
    Addendum, the updated code:
    #include <jni.h>
    #include <stdio.h>
    #include "petes_JNI_Prompt.h"
    JNIEXPORT jstring JNICALL Java_petes_JNI_Prompt_getLine
      (JNIEnv *env, jobject this, jstring prompt)
         char buf[128];
         const jbyte *str;
         str = (*env)->GetStringUTFChars(env, prompt, NULL);
         if (str == NULL)
              return NULL;  /*  OutOfMemoryError already thrown */
         printf("%s", str);
         (*env)->ReleaseStringUTFChars(env, prompt, str);
         //scanf("%s", buf);
         fgets(buf, 128, stdin);
         return (*env)->NewStringUTF(env, buf);
    }Message was edited by:
    petes1234

  • JNI System.loadLibrary troubles

    Hello again!
    I am so close to finishing this program I can taste it! But�
    OK, I am doing a bit of JNI. All appears to be well except my program can�t seem to use
    System.loadLibrary("myCPPdll");
    to find the dll file I need to run the C++ code.
    I�ve tired replacement with
    Runtime.getRuntime().loadLibrary("myCPPdll ");
    just for grins with the same result.
    I also tried
    System.loadLibrary("C:/fullPath/myCPPdll");
    with no luck.
    The error message I get, regardless if I run from the command line or via Eclipse is
    java.lang.UnsatisfiedLinkError: no myCPPdll in java.library.path.
    Possibly related: when I use the tutorial form
         Static
    System.loadLibrary("myCPPdll");
    my compiler tells me it can�t find the main. Just how critical is it to have it in this static format? It compiles great without the System call embedded in the static{} block!
    Thanks for your time!

    I added the .dll and get the same error. It was my
    understanding that System.loadLibrary(fileName)
    automatically added the file to the library path for
    the individual program in question. If this is not
    the case, could you please elaborate a bit on adding
    it to the path?
    No, in effect it searches the path to find the dll library. You need to (re-)read the tutorial -
    http://java.sun.com/docs/books/tutorial/native1.1/stepbystep/step5.html

  • JNI double trouble

    Hi,
    I have written a java application which sucessfully access the cryptoAPI functions. I am trying to convert it inot an applet. I get the following error when i open it in IE.
    before
    java.lang.UnsatisfiedLinkError: no Msgimpl in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at cryptoJNI.<clinit>(cryptoJNI.java:20)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance0(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at sun.applet.AppletPanel.createApplet(Unknown Source)
    at sun.plugin.AppletViewer.createApplet(Unknown Source)
    at sun.applet.AppletPanel.runLoader(Unknown Source)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    The following were the steps that i followed
    1.javac cryptoJNI.java
    2javah -jni cryptoJNI
    3.cl -IC:\Amsapps\WebSphere\AppServer\java\include -I"C:\Program Files\Microsoft SDK\include" -LD CryptoJNIImp.c advapi32.lib crypt32.lib -FeMsgimpl.dll
    4.jar cvf cryptoJNI.jar cryptoJNI.class
    5.jarsigner -keystore jnikeystore -storepass password -keypass passwd12 -signedjar scryptoJNI.jar cryptoJNI.jar jnikeyalias
    6.start cryptoJNI.html
    In step number 4, should the dll be also added to the jar?
    My current working directory is c:\vivek work\signedcode. I am pasting the java and the HTML file for your reference. PLease help
    cryptoJNI.java
    import java.awt.*;
    import java.io.*;
    import java.lang.*;
    import java.applet.*;
    public class cryptoJNI extends Applet {
    public void init(){
    cryptoJNI app = new cryptoJNI();
    app.crypto("My");
    private native void crypto(String store);
    static {
    System.out.println("before");
    System.loadLibrary("Msgimpl");
    System.out.println("After");
    public void paint(Graphics g) {
    g.setColor(Color.blue);
    g.setColor(Color.magenta);
    // g.drawString(test(), 120, 50);
    g.drawString("Signed 123", 120, 80);
    cryptoJNI.html
    <html>
    <title> CRYPTO JNI</title>
    <h1> Calling the keystore </h1>
    <hr>
    <APPLET CODE = cryptoJNI.class archive="scryptoJNI.jar" WIDTH=500 HEIGHT=500>
    </APPLET>
    <hr>
    </html>
    I have tried putting the MSgimpl.dll in c:\winnt\system32, but it did not work!!

    My java.library.path points to
    C:\WINNT\SYSTEM32;.;C:\WINNT\system32;C:\WINNT;C:\WINNT\SYSTEM32;C:\WINNT;C:\WIN
    NT\SYSTEM32\WBEM;C:\PROGRAM FILES\LOTUS\NOTES;C:\DMI\WIN32\BIN;c:\Program Files\
    Common Files\Adaptec Shared\System;C:\Program Files\Rational\common;C:\Amsapps\W
    ebSphere\AppServer\java\bin;C:\Program Files\Microsoft Visual Studio\Common\Tool
    s\WinNT;C:\Program Files\Microsoft Visual Studio\Common\MSDev98\Bin;C:\Program F
    iles\Microsoft Visual Studio\Common\Tools;C:\Program Files\Microsoft Visual Stud
    io\VC98\bin
    I tried putting Msgimpl.dll in one of the directories, i still get the same error. The code works perfectly if it is a non applet. DO u think this is something because of the "static" in my applet? I have pasted my applet code previously for people to have a look.

  • Having trouble with including JNI library in netbeans

    [Sorry a newbie question - I am more used to writing large amounts of Solaris kernel and writing a JNI for the first time]
    Guys,
    I have a C library that needs to hook into the Java bean. I created a JNI library wrapper around the C library using swig/javah
    and that went fine (using some of the examples/ref in this forum). The JNI library contains classes like SysInfoJNI created
    by swig.
    class SysInfoJNI {
    public final static native int NAME_LEN_get();
    public final static native int NAME_LEN_set();
    I quickly wrote a standalone test program where I did
    public class test {
    // Load JNI Library
    static {
    System.loadLibrary("SysInfo");
    public static void main(String[] args) {
    SysInfoJNI siJNI = new SysInfoJNI();
    I can compile and run this on command line doing
    javac *.java
    java -Djava.library.path=./ Sysinfotest
    and it all works fine. Now I move this code to netbeans since I need to add some more code
    and create a java->web project and pretty much transfer the code there. I add the libSysinfo.so
    using the property->library->create option but netbeans still can't see the symbols coming
    out of Sysinfo JNI library. I suspect it wants the class definitions. My question is how do I
    supply that? swig didn't really crate a header file but it did create Sysinfo.java file. Do I
    just copy Sysinfo.java in the src directory (ugly?) or is there a convention of keeping the
    *.java files in some standard place (like /usr/include for C headers) and then what would be
    the method to include SysInfo.java to my netbeans src so that symbols can be found.
    Thanks,
    Sunay

    OK, seems like I had some kind of mismatch between the library & classes.
    The loadLibrary only had the name and I had the library in /usr/lib. After running
    truss -f -t open /usr/tomcat6/bin/startup.sh >& tomcat.out
    I could see the tomcat was finding the library but still reporting link error.
    Recompiling the library and classes again and then placing the library
    in /usr/lib and classes in the right directory resolved the issue.
    So I guess the answer to my original question is that classes need to
    be delivered as a jar along with the rest of the distribution while the
    library can be delivered in /usr/lib as part of the system.
    Appreciate the help and quick responses.
    Sunay

  • Creating JNI DLL on WinXP using MinGW and GCC

    Ohh man, I spent entire day fighting with "UnsatisfiedLinkError "while trying to cal my native method. After reading all the posts with similar problems, and checking for every little thing that was suggested I figured it out. So I'm reposting the solution here since no one else had suggested this.
    The solution to my problem was that g++/gcc compiler needed an option "-Wl,--add-stdcall-alias". This was the killer. I had the "-shared", but it wouldn't link without the "-Wl,--add-stdcall-alias" option!!!
    As a summary, while its fresh in my mind, here are the trouble shooting steps I used:
    1) Check package names and the generated .h file using javah. I checked and rechecked the names, even created simpler static void method to try and get it to link.
    2) Make sure to use the "jobject" parameter for dynamic methods and "jclass" for static methods in the signature as second argument.
    3) That method name starts with "Java_" and I stress the CAPITAL "J", can not be lowercase. Although if you are using javah, that should not be the problem, since javah can not ommit this kind of detail. The only thing that you need to check for is that if you change method from dynamic to static, and don't rerun the javah, or javah doesn't replace the previous file. So make sure you restart clean and that javah regenerated the file with "jclass" or "jobject" whichever is the case.
    4) Used the "java -verbose:jni" debug flag to see my native method loaded. In my case when it wasn't working I couldn't see the method load, but there were no error messages from "System.loadLibrary" or from the verbose output. Only the UnsatisfiedLinkError. Frustrating. After the fix it loads perfectly:
    [Dynamic-linking native method org.jnetpcap.Pcap.openVoid ... JNI]5) I used "nm" found at "c:/MinGW/bin/nm.exe" to dump the symbol table, and I could see all my methods, with the appropriate named marked as text (T) flag. They were not being loaded when viewed using "java -verbose:jni" though.
    6) I put "extern "C" {}" around all my JNI C++ methods.
    7) Tried a gazilion other gcc options, posted in various messages, none worked.
    8) Finally came accross the "-Wl,--add-stdcall-alias" flag which fixed it.
    Here is a portion of my Makefile for reference:
    $(LINK_TARGET) : $(OBJS)
         g++ \
              -shared \
              -Wl,--add-stdcall-alias \
              -o $@ $^ \
              $(LIBDIRS) $(LIBS)LIBDIR and LIBS point to a single external library dependency.
    My IDE environment is Eclipse 3.2, but I run everything from Makefiles as external programs.
    I wish this was documented somewhere, would have saved me an entire day of troubleshooting.
    Cheers,
    mark...
    Message was edited by:
    voytechs - added CODE tags

    Glad my post helped out at least a few people.
    Believe it or not, I'm in the same boat now on Linux.
    Atleast I know its the name mangling problem again. I
    see a few symbols unmangled with nm, but most are,
    and those are then one's JNI is complaining about
    with UnsatisfiedLinkError.
    So now I'm going through various post related to
    linux and trying to find the same type of flag. The
    "alias" flag doesn't work with RH4 g++ version
    4.0.2.You should not need a flag on Linux. A typical compile for me on my Linux box is:
    gcc -shared -o libjnitest.so -I/usr/java/jdk1.6.0_01/include -I/usr/java/jdk1.6.0_01/include/linux jnitest.c>
    Window builds perfectly fine, but now I'm creating a
    new platform target. Everything compiles and creates
    the shared library, just can't get JNI to be happy.
    BTW, my project: http://jnetpcap.sf.net
    Ah. You have .cpp extensions on your filenames. Are you using gcc or g++ to compile? If you don't use g++, you can get errors such as:
    undefined symbol: __gxx_personality_v0
    Jim S.

  • Can anyone shed some light on HotSpot/JNI?

    I posted this to the Hotspot forum, but this place might be better ...
    Hello,
    I have just wrapped a C API in JNI.
    It pumps messages into a callback, which are then forward to the Java side via a env->CallIntMethod(object, method, jlong, jlong).
    On the java side a single accessor object is created to access the fields in the C messages. The accessors are of course JNI. A single object is created instead of a new object per message. Code snippets follow below.
    Trouble is, things are incredibly slow. A C test runs in 16 seconds, the Java version takes 6 minutes!
    A test which returns from the callback right away takes C 15 seconds and Java 26 seconds - still too long for the one single JNI call.
    I have timed some native calls from Java to C, and found JNI calls about 7-8x slower than calls to a java method.
    Even with this knowledge, I can't account for the huge performance hit.
    Is is possible that my java callback, which is called from C, and all my accessor objects which are created once and call C from Java, are not being compiled to machine code but are being interpreted? Does hotspot do its stuff on existing objects? I assumed so, but I am not sure now.
    Some code snippets follow (I can't post actual code because of NDA stuff)
    // Class is created once at the beginning of processing, and may see
    // +50million messages up to 200million or so.
    public class ABCD {
    private long swigCPtr;
    // I call this on each new message.
    void setCPtr(long ptr) {
    swigCPtr = ptr;
    // Accessor - goes to JNI to grab the C data.
    public int getUserData1() {
    return xyzJNI.get_ABCD_UserData1(swigCPtr);
    And C++ code calling Java:
    int JavaListener::onMessage(const System system, const Message message) {
    return env->CallIntMethod(jlistener, jonMessage, (jlong)system, (jlong)message);
    So now possible ideas for solutions if I can't find out what is going on:
    1. Direct memory buffers. Copy the most often used data into a buffer and then unpack it on the java side.
    2. UDP. Forward the messages via a UDP/localhost connection which I believe uses direct memory to transfer - but this is a pain, most of my JNI wrapper is autogenerated with SWIG. Is networking using JNI in java or some internal magic?
    Any comments are welcome, as I don't want to do anything for a bit - annoying having a working Java wrapper, but unusable in any application I have.
    -Ed

    Argh - once again, I find my solution right after posting this. Left out one modification to the SWIG script, now it runs in 29 seconds vs C 16 seconds, I can live with that.

  • Compilation error in creating shared library via JNI

    Hi ALL,
    I amin serious trouble with a problem. I am developing a Simulator, a function of which is to decode MPEG-2 Video files in real time and play it as well.I have got a MPEG-2 Decoder implemented in C from an open source and need to integrate with my Simulator which is writtebn in Java. The integration part I am doing via JNI(Java Native Interface). Now I have a bunch of C files in MPEG-2 decoder which are to be compiled during the Execution of the Java Simulator.Can anybody give some idea about how to call multiple C files from the Java Source through JNI at one go? Another problem I am facing is in calling a single C code from the traditional "HelloWorld" Java Code itself. The problem comes when I am trying to compile the shared library between the C native code and Java Code in my Linux Machine...I am getting the following message:
    /usr/lib/gcc-lib/i386-redhat-linux/2.96/.../../../crt1.0 : In function '_start' :
    /usr/lib/gcc-lib/i386-redhat-linux/2.96/.../../../crt1.0(.text+0x18): undefined reference to 'main'
    collect2: ld retrurned 1 exit status
    What does the above errot mean? How to rectify it.It will be of great help if you anybody can give me clues.

    It means that your compiler options are wrong.
    You need to create a shared library.
    Instead you are creating an executable, which is not the same as a shared library.
    If you search this forum you will find posts with command line options that work.

  • Passing (byref) String from Java to C++ via JNI

    I wish to pass a string to a C++ Dll as a parameter in a function. The problem is that I don't know howto receive back the data after it is filled in the C++ dll. I am trying to do what is called passing parameters by reference.
    Java Code:
    public class ABKeyBoard {
    public native long leerBanda(int pista, String datos);
    public static void main(String[] args) {
    String datos=new String();
    System.loadLibrary("ABKeyBoard");
    new ABKeyBoard().leerBanda(1,datos);
    System.out.println(datos); //the content of datos here is empty.
    C++ Code:
    Java_ABKeyBoard_leerBanda(JNIEnv *env, jobject obj,jint pista, jstring datos)
         char buffer[2024];
         memset(buffer,     0x00,     sizeof(buffer));
         strcpy(buffer, "xxxx");
         datos = env->NewStringUTF(buffer);
    return;
    Thanks for your help.

    In java every parameter are always passed by value.
    The datos parameter is a local copy of the string
    reference you pass to the method.This is wrong. The String passed to the native method is the same String object you use in Java. Although everything is passed by value in Java, what is actually passed by value is the reference to the String. This means that you can modify the object you pass, but you are not allowed to change the reference to point to a totally different object. That is where the problem is coming in.
    The trouble is that it is illegal to modify a String, even from native code. If you need to make changes in-place to the text, pass an array of chars (if your native code uses Unicode), an array of bytes (if it uses normal 8-bit characters) or a StringBuffer. You can legally modify any of these data structures with the new data. But the StringBuffer object is the only one whose length can be changed after it is created. Unfortunately it is also the hardest to use from JNI.
    Generally I think you should always pass arrays of bytes/chars to native code instead of Strings when possible. They can be modified in place, and you can use String's methods to get a byte-array in the platform's proper encoding. Using the GetStringUTFChars method is problematic because UTF only maps directly onto ASCII in the case of characters which are in the set of 7-bit ASCII characters. Your code will do wrong things if your String happens to contain some other character, unless your native code expects UTF format strings.
    The good news is that C(++) functions which return results in their arguments do not ordinarily change the length. So you should be able to allocate a byte[] or char[] ahead of time of the appropriate size (don't forget to add the trailing null, which is not a component of Java strings). I think byte[] or char[] is the best answer because you can easily map those onto C-style arrays with Get[Primitive]ArrayRegion; the return of that is suitable for passing directly to native code, as long as you have remembered the null-terminator. For instance you could do (*env)->GetByteArrayRegion(env, javaArray, 0, arrayLength, CArray) and then your CArray would be changed to point at the contents of the javaArray (note: it does not copy data into CArray, it changes CArray to point at the array contents, so do not allocate memory for CArray first). Then when you do ReleaseByteArrayRegion the results will be propagated back to Java.

  • Calling Java from Delphi via JNI

    Hi all. I've got a J2EE application, and I'm trying to write a Delphi client for the server. More specifics:
    Server and test client running in Win2000 SP4.
    Server running in JBoss (JUnit test cases have successfully connected to the server)
    JDK 1.4
    I'm using some Delphi files from JEDI which allow me to load/access a JVM via JNI. So far, I've been able to:
    1) Create a Properties object.
    2) Populate the Properties object with String values (making sure to use NewStringUTF to pass into the Properties method
    3) Find my java client classes which facilitate opening a connection.
    However, when I attempt to call the method on the object which actually creates the connection, I get an Exception.
    My immediate question is how do I see what the Exception is? I have an Exception object, but ExceptionDescribe doesn't product anything, and I'm having trouble finding any details about the Exception (what type of exception, what the Message or Call Stack is). At the moment, something's wrong but I can't see what. And I'll have no chance of fixing it if I don't know what the problem is.
    Thanks for any help,
    Ed

    I use some code for solving this task (in real project with Delphi 6.0 & Java 1.4.1).
    May be, it will help.
    procedure TJavaInterp.CheckJNIException(Message : string);
    begin
    if JNI_ExceptionCheck(JNIEnv) = JNI_TRUE then
    begin
    JNI_ExceptionDescribe(JNIEnv);
    JNI_ExceptionClear(JNIEnv);
    raise Exception.Create(Message);
    end;
    end;{ TJavaInterp.CheckJNIException }
    procedure TJavaInterp.HandleException(excpt : jthrowable);
    var
    Msg: string;
    ESyntax : Exception;
    CauseName : WideString;
    Tag : OleVariant;
    begin
    if JNI_IsInstanceOf(JNIEnv, excpt, FclsCommonSyntaxError) = JNI_TRUE then
    begin
    ESyntax := Self.BuildSyntaxException(excpt);
    JNI_DeleteLocalRef(JNIEnv, excpt);
    raise ESyntax;
    end;
    Msg := Self.GetMessage(excpt);
    if JNI_IsInstanceOf(JNIEnv, excpt, FclsNPScriptRuntimeException) = JNI_TRUE then
    begin
    CauseName := Self.GetCauseName(excpt);
    Tag := Self.GetTag(excpt);
    JNI_DeleteLocalRef(JNIEnv, excpt);
    raise NPScriptHelper.BuildNPScriptRuntimeException(Msg, CauseName, Tag);
    end;
    if JNI_IsInstanceOf(JNIEnv, excpt, FclsHaltException) = JNI_TRUE then
    begin
    JNI_DeleteLocalRef(JNIEnv, excpt);
    raise Exception.Create(Msg);
    end;
    Msg := Self.ToString(excpt);
    JNI_DeleteLocalRef(JNIEnv, excpt);
    raise Exception.Create(Msg);
    end;{ TJavaInterp.HandleException }

  • Java 1.5 JNI and C++ exception

    Hello, All
    I've troubles with handling C++ exceptions using JNI and shared library. I'm using Java 1.5_06, RedHat 7.3 and JBoss 4.0.5
    From Java class I call JNI a method in my shared library(libx.so) which calls a method in other shared library(liby.so). Liby.so uses Xerces library. During parsing process an exception occurs. But according to Xerces sources it's a normal behavior and should be caught. But instead I've got SIGNABRT in JVM and a core dump will created. What's wrong? Backtrace shows similar something:
    XXXXX  __default_terminate() ....
    XXXXX  __terminate() ....
    XXXXX  __throws
    XXXXX C++ method ..
    XXXXX.....
    XXXXX.....
    XXXXX  JNI methodI found similar bugs reports in the forum. But they says about Java 1.4 version and according to bugs descriptions it should be already fixed.
    Message was edited by:
    kostik78

    The question is closed. The root cause was incorrect building of shared library.

  • Using C functions with JNI

    Hello,
    I am just looking at JNI for the first time today. I have to write some utility functions in C for the a linux Red Hat 7 server, and then be able to call them from java applications. I am having some trouble when I try and compile the c source. I am not sure if this is a C error directly, or caused by the java. I am really sorry if this is a C error, its been awhile! I am simply trying to runt the demo on the java.sun.com site. Here is my code:
    The Java:
    public class HelloWorld {
    public HelloWorld() {
    public native void displayHelloWorld();
    static {
    System.loadLibrary("hello");
    public static void main(String[] args) {
    new JNITest2().displayHelloWorld();
    The c file:
    #include <jni.h>
    #include "JNITest2.h"
    #include <stdio.h>
    JNIEXPORT void JNICALL
    Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj)
    printf("Hello world!\n");
    return;
    The .h file:/* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class HelloWorld */
    #ifndef IncludedHelloWorld
    #define IncludedHelloWorld
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class: HelloWorld
    * Method: displayHelloWorld
    * Signature: ()V
    JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld
    (JNIEnv *, jobject);
    #ifdef __cplusplus
    #endif
    #endif
    The Error I Get:
    [2943UK@hercules classes]# cc -g -I/usr/local/jdk1.3/include -I/usr/local/jdk1.3/include/linux HelloWorldImp.c -o libhello.so
    /usr/lib/gcc-lib/i386-redhat-linux/2.96/../../../crt1.o: In function `_start':
    /usr/lib/gcc-lib/i386-redhat-linux/2.96/../../../crt1.o(.text+0x18): undefined reference to `main'
    collect2: ld returned 1 exit status
    Thanks in advance to anyone who knows the answer and can help me.
    Ian

    Sorry, Here is the java source I am using:
    public class HelloWorld {
    public HelloWorld() {
    public native void displayHelloWorld();
    static {
    System.loadLibrary("hello");
    public static void main(String[] args) {
    new HelloWorld().displayHelloWorld();
    }

  • Array of array in JNI

    I have a problem that I've been stuck on for the last few days. I can get one array back from JNI side to java side, but I couldn't get two dimension array back from JNI to JAVA side
    JNI side
    JNIEXPORT jint JNICALL Java_JNITest_TestCall
    (JNIEnv *env, jclass instance, jobject outJava)
    OutStruct outObj; // local structure that the C function fills in
    jintArray row_flags = (jintArray)(*env)->NewIntArray(env, 5);
    jobjectArray arrayOfArrays_tmp = (jobjectArray)(*env)->NewObjectArray(env, 3, (*env)->GetObjectClass(env, row_flags), 0);
    jintArray intArr_tmp = (*env)->NewIntArray(env, 5);
    jclass objClass = (*env)->GetObjectClass(env,outJava);
    jfieldID intNum = (*env)->GetFieldID(env, objClass, "javaIntNum", "I");
    jfieldID intArr = (*env)->GetFieldID(env, objClass, "javaIntArr", "[I");
    jfieldID arrayOfArrays = (*env)->GetFieldID(env,objClass,"javaArrayOfArrays","[Ljava.lang.reflect.Array");
    // call C function to fill in outObj
    (*env)->SetIntField(env, outJava,intNum,outObj.bag_roi->xmin);
    for (j=0;j<=outObj.bulks->number_of_bulks;j++) {
    (*env)->SetIntArrayRegion(env,intArr_tmp,j,1,&outObj.bulks[j].xmin); // this works
    (*env)->SetIntArrayRegion(env,row_flags,0,5,&outObj.bulks[j].flags[0]); // this doesn't work
    // I want an array of outObj.bulks[j].flags (which is an array of ints) in my java class
    (*env)->SetObjectArrayElement(env,arrayOfArrays_tmp,j,row_flags); // this doesn't either
    (*env)->SetObjectField(env,outJava,intArr,intArr_tmp);
    Java class that corresponds with outJava is as follows:
    import java.io.*;
    import java.util.*;
    public class JOutClass{
    public int javaIntNum;
    public int[] javaIntArr = new int[5];
    public int[][] javaArrayOfArrays = new int[3][5];

    Hi, maybe you can glean something from this test case I created when I was fighting with this. We seem to have taken slightly different approaches, but see if it helps at all. The trouble might be that you did not release the array(s) back to the java memory space with ReleaseIntArrayElements.
    Also, because the hardcoded array lengths seem unavoidable ...remember that a public final static int field in the class that you compile against jni will also be available in the .h file (not shown in this example). It's still hardcode ...but at least you can alter the constant in the Java class without having to recompile the native code. Anyway, here you go. I have a 3D array example as well ...but that was just plain sick, so I will spare you the nausea.
    File TestRaster2DImp.c
    #include <jni.h>
    #include "TestRaster2D.h"
    JNIEXPORT void JNICALL
    Java_TestRaster2D_nextGeneration(JNIEnv *env, jobject obj, jobjectArray arr)
      int i, j;
      jint *body[2];
      jintArray oneDim[2];
      jsize len1;
      jsize len2;
      oneDim[0] = (*env)->GetObjectArrayElement(env, arr, 0);
      len1 = (*env)->GetArrayLength(env, arr);
      len2 = (*env)->GetArrayLength(env, oneDim[0]);
      for(i=0; i<len1; i++) {
        oneDim[i] = (*env)->GetObjectArrayElement(env, arr, i);
        body[i] = (*env)->GetIntArrayElements(env, oneDim, 0);
    for(j=0; j<len2; j++) {
    body[i][j]++;
    printf("%d\n", body[i][j] );
    printf("\nOut: %d\n", body[0][2] );
    printf("Out: %d\n", body[1][2] );
    (*env)->ReleaseIntArrayElements(env, oneDim[0], body[0], 0);
    (*env)->ReleaseIntArrayElements(env, oneDim[1], body[1], 0);
    File TestRaster2D.java
    public class TestRaster2D {
      int[][] ra = {
        { 1, 2, 3, 4, 5 },
        { 11, 12, 13, 14, 15 }
      public TestRaster2D() {
        System.out.println( " is " + ra[0][2] );
        System.out.println( " is " + ra[1][2] );
        System.out.print( "\n" );
        nextGeneration( ra );
        System.out.print( "\n" );
        System.out.println( " is " + ra[0][2] );
        System.out.println( " is " + ra[1][2] );
      public native void nextGeneration( int[][] theArray );
      static {
        System.loadLibrary("raster2D");
      public static void main(String[] args) {
        new TestRaster2D();
    }Good luck.

  • JNI and Websphere 3.5

    Hi there,
    I have an application that makes use of JNI technology.
    Basically, so as to work, the app must access a C++ DLL library via JNI, that in my case is a set of classes packaged in a jar file.
    The app works just fine when is run locally, but I?m really in trouble to set up WebSphere properly so that I can web access the app with servlet and jsp.
    I haven?t been succesful getting consistent info anywhere.
    Could anybody give me detailed instructions on how to do that?
    IBM instructions lack further details, they just don?t help, they?re made for experts!
    Thanks!

    I have solved the previous problem, and fallen into another.
    Now this is quite a wierd one. Basically, as the servlet is run from the browser, the servlet calls the business classes. The business classes use other java classes that have native methods to call a DLL library.
    A have put the JNI java classes in the websphere class path, not in the web app classpath, as descrived in the IBM redbooks, and I also created the 'path' variable from the web project in WebSphere in reference to the DLL.
    When I go to the browser and call the servlet, the app works, once I get all the info on the jsp that came from the DLL. Now, if any other call is done through the web browser, the dll is no more instantiated!
    Neither from the same machine nor from anywhere else!
    Has anybody ever seen such a thing?
    I just don?t know what else to do, and have not found any more instructions.
    Please, any info on it is very much welcome.
    Thanks a lot.

Maybe you are looking for

  • My iMac keeps crashing randomly and restarting with error

    I have asn iMac 2009 intel running OSX 10.8.4 it keeps randomly crashing and restarting with error message "your compter crashed because of a problem" Process:         rapportd [222] Path:            /Library/Rapport/*/rapportd Identifier:      rappo

  • Safari will not open, freezes and closes

    When I go to open Safari, it starts but hangs.  After a period it closes and lists the problem as crash in Thread 6 Safari: SnapshotStore.  I cannot select preferences to maybe disable java or anything else since it stalls almost immediately.

  • Apex 4.2 developer page not showing up after installing over 10g

    Hi there, So as luck would have it my Win XP OS crashed. Yes, its the office laptop and I cannot upgrade the OS for now. Anyhow, I got the whole machine re-imaged and installed 10g which had version 2.1 and everything was okay. I was earlier running

  • Can't stop Pop up ads on yahoo home page

    Hi, I have 3GS with latest 4.3.3 os.  Last couple of days, every time I open yahoo home page (uk.m.yahoo.com) I get pop up ad at bottom of the page. Clicking on the close button only removes it to a tap that appears at edge of screen. If I open the a

  • IOS8 wifi or 3G its going on and off all the time, and if its on  its very slow.

    i have this problem since i update my iPhone 5s.  My internet is oky. and I'm sure something happen because the IOS8.