NewObject crash in a PLI/C/JNI code

Hi,
i call NewObject() function in a PLI/C/JNI app to create a java/lang/Vector instance.My Verilog simulator (ModelSim PE 5.4b) crash without display an error code.
Please take a look , and see what is wrong with my code.
jclass jclass_Vector;
jmethodID jmethodID_Vector_new;
jclass_Vector=_env->FindClass("java/util/Vector");
if(jclass_Vector==NULL){
return ;
jmethodID_Vector_new=_env->GetMethodID(jclass_Vector,"<init>","()V");
if(jmethodID_Vector_new==NULL){
return ;
jobject dataVector;
dataVector=_env->NewObject(jclass_Vector,jmethodID_Vector_new);
Thanks in advance,
Marius

As far as I can tell, there's nothing wrong with the small snippet of code that you've posted. The problem is elsewhere. Try making a small sample program that demonstrates the failure.
Also, take a look at Jace - http://jace.reyelts.com/jace
The equivalent code would be:
// Create a new Vector
Vector dataVector(); A lot simpler...
God bless,
-Toby Reyelts

Similar Messages

  • JVM core dump - JNI code

    I am using JNI in my Java application , 12 hours after running my test case get a JVM crash -
    1) These are the parameters with which i invoke my Java program
    java -d64 -Xcheck:jni -Xmx2560M -Xms2560M -Xss256k RunQueries
    2) The Heap output at the time of the core shows "from space" as 100% used , does this signify anything?
    Heap at VM Abort:
    Heap
    def new generation total 848128K, used 672342K [0xfffffffe93c00000, 0xfffffffec9150000, 0xfffffffec9150000)
    eden space 822464K, 78% used [0xfffffffe93c00000, 0xfffffffebb385b90, 0xfffffffec5f30000)
    from space 25664K, 100% used [0xfffffffec7840000, 0xfffffffec9150000, 0xfffffffec9150000)
    to space 25664K, 0% used [0xfffffffec5f30000, 0xfffffffec5f30000, 0xfffffffec7840000)
    tenured generation total 1747648K, used 1350866K [0xfffffffec9150000, 0xffffffff33c00000, 0xffffffff33c00000)
    the space 1747648K, 77% used [0xfffffffec9150000, 0xffffffff1b884830, 0xffffffff1b884a00, 0xffffffff33c00000)
    compacting perm gen total 16384K, used 13550K [0xffffffff33c00000, 0xffffffff34c00000, 0xffffffff37c00000)
    the space 16384K, 82% used [0xffffffff33c00000, 0xffffffff3493b860, 0xffffffff3493ba00, 0xffffffff34c00000)
    Local Time = Mon Feb 12 21:49:40 2007
    Elapsed Time = 61687
    # The exception above was detected in native code outside the VM
    # Java VM: Java HotSpot(TM) 64-Bit Server VM (1.4.2_07-b05 mixed mode)
    3) A dbx on the Java core shows the location in the JNI code where the core dump occured.
    dbx `which java` core
    For information about new features see `help changes'
    To remove this message, put `dbxenv suppress_startup_message 7.3' in your .dbxrc
    Reading java
    dbx: internal warning: writable memory segment 0x7cb00000[16384] of size 0 in core
    core file header read successfully
    Reading ld.so.1
    Reading libthread.so.1
    Reading libdl.so.1
    Reading libc.so.1
    Reading libc_psr.so.1
    Reading libjvm.so
    Reading libCrun.so.1
    Reading libsocket.so.1
    Reading libnsl.so.1
    Reading libm.so.1
    WARNING!!
    A loadobject was found with an unexpected checksum value.
    See `help core mismatch' for details, and run `proc -map'
    to see what checksum values were expected and found.
    dbx: warning: Some symbolic information might be incorrect.
    t@1 (l@1) terminated by signal ABRT (Abort)
    0xffffffff7eea822c: lwpkill+0x0008: bcc,a,pt %icc,_lwp_kill+0x18 ! 0xffffffff7eea823c
    Current function is Java_getLoid (optimized)
    7239 e = cod_to_long (*(o_object*) data, &loid_as_long);
    (dbx) where
    current thread: t@1
    [1] lwpkill(0x0, 0x6, 0xffffffffffffffe6, 0x0, 0x0, 0x0), at 0xffffffff7eea822c
    [2] raise(0x6, 0x0, 0xffffffff7fffad30, 0x7fbffeff00003ff6, 0x0, 0x2), at 0xffffffff7ee58a8c
    [3] abort(0x0, 0xffffffff7fffae10, 0x0, 0xfffffffffffffff8, 0x0, 0xffffffff7fffae39), at 0xffffffff7ee3e3b8
    [4] os::abort(0x1, 0xffffffff7e9d295c, 0xffffffff7fffaf10, 0xffffffff7e9d24a9, 0x4b007c, 0xffffffff7eb78878), at 0xffffffff7e90951c
    [5] os::handle_unexpected_exception(0x10011e600, 0xa, 0xfffffffe90345704, 0xffffffff7fffbeb0, 0xffffffff7e69c6f8, 0x0), at 0xffffffff7e907e08
    [6] JVM_handle_solaris_signal(0xffffffff7fffbeb0, 0xffffffff7e9d443e, 0xffffffff7fffbbd0, 0x1, 0x0, 0x1), at 0xffffffff7e69c800
    [7] __sighndlr(0xa, 0xffffffff7fffbeb0, 0xffffffff7fffbbd0, 0xffffffff7e69cb9c, 0x0, 0x0), at 0xffffffff7f2188d8
    ---- called from signal handler with signal 10 (SIGBUS) ------
    =>[8] Java_getLoid(vjEnv = ???, cls = ???, handle = ???, attr = ???) (optimized), at 0xfffffffe90345704 (line ~7239) in "j.c"
    I have added checks for this function call to ensure that no invalid pointer is being sent to it which could cause a segmentation violation.
    Please could someone give me some pointers on how to solve this problem, the error occurs at this point only 12 hours after running the test case..

    First step is to add the option -Xcheck:jni to your java command line. It will flag common JNI errors.
    If that doesn't identify the problem, then compile your jni code with debugging symbols (-g) and add the following option to the java command line when you run your test: -XX:+ShowMessageBoxOnError. When you hit the problem again, the VM will keep the process alive instead of calling abort(). Then you can use dbx to attach to the live process and should be able to get a better idea of what went wrong.

  • JVM Seg Fault With Multithreaded JNI Code

    Hello all:
    I'm having a problem with a multi threaded application. The application is used to bridge an exsisting C++ application with an exsisting Java application so I went with a JNI implementation. After I completed my implementation, I found that the bridge would crash after a few hours (or a few million JNI calls). At first I thought there was a memory leak but my memory usage was not going up (according to the task manager) and the heap was staying around 3 MB (according to a third party tool). I finally figured out that the problem was my JNI code. The JNI code is all in a wrapper DLL (built with MinGW) that four other DLL's call dynamically. So I made a test app to test the wrapper dll. The test app is a simple two threaded application that creates a java object and deletes the java object. CODE:
    #include <process.h>
    #include "JNIUtilityInterface.h"  // Link to the JNI dll (GetProcAdress, etc.)
    void test(void * arg) {   
       for (int i = 0; i < 4000000; i++) {
          jobject jTest = createObjectByClass(NULL, "JNITest", "()V");
          deleteObject(jTest);
       int num = (int)arg;
       printf("done - %d\n", num);              
    int main(int argc, char *argv[])
       clearJNIUtilityDll();
       initJNIUtilityDll();
       invokeJVM();         
       for (int i = 0; i < 3; i++) {
          if (i == 0) {
             _beginthread(test, 0, (void*)i);
          } else {           
             _beginthread(test, 0, (void*)i);
       Sleep(240000);
       exitJNIUtilityDll();
       return 0;
    }createObjectByClass code:
    jobject JNIUtility_API createObjectByClass(jboolean * hasException, 
                                               const char * className, 
                                               const char * descriptor, va_list args) {                                                                                                                    
       jclass clazz;
       jmethodID mid;
       jobject obj;
       JNIEnv * env;
       env = getEnv();
       if (env != NULL) {  
          if (env->EnsureLocalCapacity(2) == JNI_OK) {
             jclass clazz = env->FindClass(className);                                                
             jmethodID mid = env->GetMethodID(clazz, "<init>", descriptor);       
             if (mid) {
                obj = env->NewObjectV(clazz, mid, args);                                             
             env->DeleteLocalRef(clazz);          
          if (hasException) {
             *hasException = env->ExceptionCheck();
       env = NULL;
       return obj;
    } getEnv code:
    JNIEnv * getEnv() {          
       JNIEnv * env;
       jint result;
       result = jvm->GetEnv((void **)&env, JNI_VERSION_1_4);
       if (result == JNI_EDETACHED) {
          if (jvm->AttachCurrentThreadAsDaemon((void **)&env, NULL) == JNI_OK) {
             //printf("Attached current thread!\n");
       return env;
    }deleteObject code:
    void JNIUtility_API deleteObject(jobject obj) {
       JNIEnv * env;
       env = getEnv();
       if (env != NULL) {                                                                                                                                               
          env->DeleteLocalRef(obj);
       env = NULL;                             
    }The other code is not important since I know this is where the seg fault is happening. Again this is just test code but when I run this code with only one thread, it works fine (with the 4000000 for loop). The JavaVM is globally cached as well.
    If anybody nows how to properly run two or more native threads that use JNI methods, please let me know or if you have any tips, that will be good too! If you want any more code to try for yourself, I'm willing to send it to you.
    Thanks!!

    Nevermind, I found out that if you build you code using jni.h from 1.5.0_06 and run you code using 1.5.0_04 JRE, you run into problems with multi threading! Don't do this because it leads to headaches and high blood pressure :)

  • Need to use default package for JNI code?

    Hi,
    I don't have much experience with JNI code, so excuse me if I make a silly mistake.
    I have a set of DLLs to interface with Microsoft native speech code ("Microsoft Sam") -- a GPL library called Quadmore. Quadmore has some sample Java code to work with the libraries, all of which they put in the default package (no package). If I move their code to a named package, it breaks. The Java code is able to load th libraries, but can't find any of the methods.
    Looking at the source for their DLLs (though I don't speak C++), the method names are things like
    JNIEXPORT jboolean JNICALL Java_QuadmoreTTS_SpeakDarling(JNIEnv *env,jobject obj,jstring strInput)As far as I understand, this implies that the QuadmoreTTS.class that calls the code must be in the default package, as otherwise the method name needs to be prepended with a package name.
    If that's so, then there's no way I can use the code as-is, right? Naturally, the rest of my program is in named packages, and I can't import any class that is in the default package, right? I've tried placing all their code in a jar and adding the jar to my classpath, but I still can't import any of their classes as they are in the default package.
    Is the only solution to re-compile all their C/C++ code to let it use packages? Am I being dumb and missing something? I'm pretty sure other people have used Quadmore before, so I can't believe that they've never had this problem before.
    Any suggestions greatly appreciated!
    Sam

    C/C++ functions in JNI must conform to the prototypes produced by running the javah compiler against the class file with native methods in it. So if you move the class to another package, the prototypes change. If you doun't change the compiled C coudes to suit, you will get undefined method errors when you load the dll as the JVM won't be able to match the native methods to the methods in the dll (it will call WinLoadLibrary() and WinLoadProcAddress() or somesuch under Windows).

  • My JNI codes get NoSuchMethodException when release to user

    My JNI codes run well in my development environment(JBuilder7), but when they release to user, they get java.lang.NoSuchMethodException. The error generates when the C++ code try to call the java side method.
    The release package was built by my colleague. And I found that they obfuscate my codes after the normal build work.
    So I wonder is this the reason I got NoSuchMethodException ?
    Thanks in advance!

    Yes. I have figured out that it is the obfuscator causes the problem.
    I have spent too much time and energy in sloving the problem, so I think it might be worthwhile to write down what I have learned and let others avoid the same pitfall.
    A common trick played by obfuscate is to change the method and variable, so that a line of code that once said:
    draw(imageList.get(i));
    may change to
    a(b.a(c));
    When my c++ code try to call the java-side code using GetMethodID(..."draw"...) or GetStaticMethodID(..."draw"...), it will, of course, cause the NoSuchMethodException
    After I skipping obfuscating the Java classes called by the c++ codes, the problem solves.
    Thank you very much

  • How to manage the memory within this JNI code

    This is a piece of JNI code that i had written..........
    i am calling these methods in a infinite loop to listen for changes......
    if a change has occured it shpuld get changed. other wise not....
    But the memory is allocated 4 bytes every second.... even if the user doesnt makes a change....... ( memory increases with TIME....... )
    How to get rid of this problem
    Please Help!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #include <jni.h>
    #include "ParameterClass.h"
    #include <stdio.h>
    #include <scrpcdll.h>
    const char *NetAddr = "";
    const char *str = NULL;
    int sp= 0;
    double value= 0;
    jsize doubleLen = 0;
    jsize strLen = 0;
    int val=0;
    int i= 0 ;
    jdouble *body = NULL;
    const char *name = NULL;
    jstring *string = NULL;
    const char *tableStr = NULL;
    int sp1 = 0;
    double value1 = 0;
    JNIEXPORT jdouble JNICALL
    Java_ParameterClass_IdentificationValue(JNIEnv *env, jobject obj,jstring parameterName,jdouble parameterValue)
         if(SC_ConnectToSoftcar(NetAddr))
              str = (*env)->GetStringUTFChars(env,parameterName,NULL);
              sp = SC_AddVari(str, 6, "M");
              SC_Set(sp,parameterValue);
              (*env)->ReleaseStringUTFChars(env,parameterName,str);
              (*env)->ReleaseStringUTFChars(env,parameterName,NULL);
              value = SC_Get(sp);
         (*env)->DeleteLocalRef(env,parameterName);
         return value;
    JNIEXPORT void JNICALL
    Java_ParameterClass_OnlineValue(JNIEnv *env1,jobject obj1,jobjectArray str,jdoubleArray doArr)
         if(SC_ConnectToSoftcar(NetAddr))
              doubleLen = (*env1)->GetArrayLength(env1, doArr);
              strLen = (*env1)->GetArrayLength(env1,str);
              body = (*env1)->GetDoubleArrayElements(env1,doArr,NULL);
              for(i = 0; i < doubleLen; i++)
                   *string = (jstring)(*env1)->GetObjectArrayElement(env1,str,i);
                   name = (*env1)->GetStringUTFChars(env1,*string,NULL);
                   val = SC_AddVari(name, 6, "revs");
                   SC_Set(val,body);
                   (*env1)->ReleaseStringUTFChars(env1,*string,name);
                   (*env1)->ReleaseStringUTFChars(env1,*string,NULL);
              (*env1)->ReleaseDoubleArrayElements(env1,doArr,body,0);
              (*env1)->DeleteLocalRef(env1, *string);
         SC_DisconnectFromSoftcar();
         return;

    Hai,
    Thanks for your comments.......
    In Java i call the JNI methods inside a Infinite loop...
    when i comment this Infinite loop then the memory doesnt Increase at all.....
    but i cannot comment since i need a functionality to execute through JNI.....
    so if i uncomment this Infinte loop then i get a Probelm.........
    This is the JAVA CODE which calls JNI CODE:::::::::::::::::::::
    while(loopForever)
         streamWrite();
         System.gc();
    public void streamWrite()
    // Getting the Parameter Value from the Softcar
         for(i = 0; i < newparameterArray.length; i++)
              newparameterArray[i] = valueClass.returnIdentificationValue(prefix+parent.parameterName);
              System.gc();
    /*Checking the Array of values: Checking which value of the Array has changed in Softcar      Checking for the Elements of the Array which had been changed by the User if the change is made then Updating to the ASAP-3 Server.........*/
         if(Arrays.equals(parameterArray,newparameterArray) == true)
              for(i = 0; i < newparameterArray.length; i++)
              newparameterArray[i] = valueClass.returnIdentificationValue(prefix+parent.parameterName[i]);
              System.gc();
         else{
              for(i = 0; i < newparameterArray.length; i++)
                   if(parameterArray[i] != newparameterArray[i])
                        parameterArray[i] = newparameterArray[i];
                             parent.commandparameters.setapsparameters.parameterField.setText(parent.parameterName[i]);
                             parent.commandparameters.setapsparameters.parameterValueField.setText(Double.toString(newparameterArray[i]));
              try{
                   bos.write((byte[])parent.commandparameters.setapsparameters.setParameterArray());
                   bos.flush();
                   Thread.sleep(500);
                   readfromStream();
                   serverResponse();
              }catch(IOException exception){System.err.println(" Write Stream Exception" + exception.getMessage());}
              catch(InterruptedException ie){System.err.println(ie.getMessage());};
              //parameterArray[i] = newparameterArray[i];
              System.gc();
    //Getting the TableValue from Softcar.......
              for(j = 0; j < Integer.parseInt(parent.xDimension); j++)
                   newtableValueArray[j] = valueClass.returngetTableValue(arrayString[j]);
                   System.gc();
    //Comparing the Values ( whether the user has chaged the TableValue )
              if(Arrays.equals(tableValueArray,newtableValueArray) == true)
                   for(j = 0; j < newtableValueArray.length; j++)
                        newtableValueArray[j] = valueClass.returngetTableValue(arrayString[j]);
                        System.gc();
              else
                   for(j = 0; j < newtableValueArray.length; j++)
                        if((tableValueArray[j] != newtableValueArray[j]))
                             tableValueArray[j] = newtableValueArray[j];
                             parent.commandparameters.setlookupparameters.yindexField.setText(parent.yDimension);
                             parent.commandparameters.setlookupparameters.xindexField.setText(Integer.toString(j+1));
                             parent.commandparameters.setlookupparameters.valueField.setText(Double.toString(newtableValueArray[j]));
                             try{
                                  bos.write((byte[])parent.commandparameters.setlookupparameters.setlookupArray());
                                  bos.flush();
                                  Thread.sleep(500);
                                  readfromStream();
                                  serverResponse();
                             }catch(IOException exception){System.err.println(" Write Stream Exception" + exception.getMessage());}
                             catch(InterruptedException ie){System.err.println(ie.getMessage());};
                             System.gc();

  • SoS, windows freezing when debugging jni code

    Somebody Help!!!!
    I am desperately trying to debug JNI code with MSDEV debugger.
    This is a flow:
    1. I run the java application from Msdev. Visual 6.0
    2. Insert a breakpoint in the first native method.
    3. The program successfully stops in the breakpoint.
    4. The "next" debugger command freezes WINDOWS :(
    I have tried all last jdk2 releases starting from 1.3 till 1.5.
    Any ideas ?
    10000000x in advance

    Cross-post:
    Duplicate post:
    http://forum.java.sun.com/thread.jspa?threadID=604754
    @OP: QUIT IT!

  • Porting JNI code to x64

    I am trying to port some existing JNI code so that it can run on 64 bit platforms as well as the existing 32 bit platforms. The one issue I cannot seem to solve is what to do with variables which are linked to the platform size.
    For example, a variable which is delared as size_t will be 32 bits on the 32 bit platforms, but will be 64 bits on the 64 bit platforms.
    I cannot find any JNI defines that match this paradyme.

    What do you mean?
    Are you trying to create a single compiled instance that runs on both platforms?
    Or are you trying to create a code base that, when compiled appropriately, runs on one or the other?
    Java types are java types. So you use what ever it gives you. If you want to translate it to a C/C++ type then you are going to have to do something different, possibly via preprocessor directives.

  • JNI code generator

    Hi all
    We are planning to use a library(written in fortran) for a particular data format (all binary).we also have the "C Wrappers" around the fortran code.We cannot re-write the whole thing in java since it was written around 20 yrs back and we don't have any knowledge of fortran,also it takes lot of man power to learn and understand and then re-implement it.So we are looking for a automatic JNI code generator for these C wrappers.
    I found that there's one called SWIG but user recommendation was less for it.so do we have any other tools available??
    thanks
    Sree

    You may also create a DLL from the C wrapper then use a generic Java/DLL wrapper to call those exported functions.
    There are plenty of generic wrapper, commercial or free.
    For example JNative is the tool I develop under LGPL and use.
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Help! JNI code freezes inside printf() call

    Hi,
    I have a JDK 1.1.8 based java app that loads a JNI based dll. When I run the app from DOS prompt it is working fine. When I run the app from my IDE (i.e no access to console stdout/stdin), the app is freezing. So I launched VC++ 6x and attached to the Java app. Found that the JNI code that was trying to print trace messages using std C call "printf()" freeze inside printf().
    Is the lack of std dos command window an issue when running an app like this?
    I appreciate any pointers.
    Thanks
    Puri malluru

    Is the lack of std dos command window an issue when running an app like this?Could be. If the output is being redirected and the pipe is filling then the io method will block until the pipe clears. Perhaps the IDE has an output window that you need to open or init.

  • Causing the JNI code to crash "properly"

    Hi,
    I have some code written in C and liked to Java using JNI.
    When I run it (even from the Visual C++ environment) and the code gets an exception in C, the JVM catches it and closes up nicely with an error.
    What can I do to remove this behavior and let it crash - this will cause Visual C++ debugger to catch it and show me where the crash is.
    Thanks,
    Tsahi

    Hi,
    I've got 2 problems with this:
    1. I'm writiing code in pure ANSI C - so try/catch doesn't work for me in the long run - just as a way of debugging a specific problem.
    2. I need something that will crash - not something that will get over it, but something that will be able to show me the exact problem, along with a backtrace, values of variables, and the ability to use a debugger to check the memory while I'm at it.
    I will try it though, so thanks a lot

  • Help me debug this JNI Code

    Hi all i've got this third party DLL with a source code downloaded
    and this JNI method has a memory leak problem. The hard part is i can't
    seem to find it resources seem to be properly released. This code is
    kind of long any suggestions are welcomed.
    JNIEXPORT jobject JNICALL Java_ca_beq_util_win32_registry_RegistryKey_getValue(JNIEnv *env, jobject obj, jstring name) {
    // get the root key (RootKey) from the RegistryKey (this.getRootKey.getValue())
    int nRootKey = getRootKey(env, obj);
    // get the path (String) from the RegistryKey (this.getPath())
    // get reference to RegistryKey class
    jclass CRegistryKey = env->GetObjectClass(obj);
    // get field ID of path string
    jfieldID fid_path = env->GetFieldID(CRegistryKey, "path", fieldDescriptor::jfd_String);
    if(fid_path == NULL) { return NULL; }
    // get reference to path string
    jstring path = (jstring)env->GetObjectField(obj, fid_path);
    if(path == NULL) { return NULL; }
    // convert to native string
    const char *szPath = env->GetStringUTFChars(path, NULL);
    if(szPath == NULL) { return NULL; }
    // open registry key for reading
    HKEY hkey;
    if(RegOpenKeyEx((HKEY)nRootKey, szPath, 0, KEY_READ, &hkey) != ERROR_SUCCESS) {
    env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Error opening registry key");
    env->ReleaseStringUTFChars(path, szPath);
    return NULL;
    } // if
    else {
    const char *szName = env->GetStringUTFChars(name, NULL);
    // find the type and size of the value
    DWORD type;
    DWORD size;
    if(RegQueryValueEx(hkey, szName, NULL, &type, (LPBYTE)NULL, &size) != ERROR_SUCCESS) {
    env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Error retreiving registry value");
    RegCloseKey(hkey);
    env->ReleaseStringUTFChars(name, szName);
    return NULL;
    } // if
    // get memory to hold the value
    char data = (char)malloc(size);
    // read the value
    if(RegQueryValueEx(hkey, szName, NULL, &type, (LPBYTE)data, &size) != ERROR_SUCCESS) {
    env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Error retreiving registry value");
    free(data);
    RegCloseKey(hkey);
    env->ReleaseStringUTFChars(name, szName);
    return NULL;
    } // if
    RegCloseKey(hkey);
    env->ReleaseStringUTFChars(name, szName);
    char* szField; // set to string version of registry type
    jobject dataValue; // data to be passed in RegistryValue.setData()
    jclass CInteger; // java.lang.Integer for DWORD base types
    jmethodID mid_IntegerConstructor; // java.lang.Integer.Integer(int) for DWORD base types
    char *tmp;                          // buffer, used when expanding REG_EXPAND_SZ types
    DWORD required; // buffer size, used when expanding REG_EXPAND_SZ types
    // convert the registry data to a Java type
    switch(type) {
    // raw, unformatted, binary data
    case REG_NONE:
    case REG_BINARY:
    if(type == REG_NONE) {
    szField = "REG_NONE";
    } // if
    else {
    szField = "REG_BINARY";
    } // else
    dataValue = env->NewByteArray(size);
    if(dataValue == NULL) { return NULL; }
    env->SetByteArrayRegion((jbyteArray)dataValue, 0, size, (signed char*)data);
    break;
    // integer/long values
    case REG_DWORD:
    case REG_DWORD_BIG_ENDIAN:
    if(type == REG_DWORD) {
    szField = "REG_DWORD";
    } // if
    else {
    szField = "REG_DWORD_BIG_ENDIAN";
    } // else
    CInteger = env->FindClass(classDescriptor::jcd_Integer);
    if(CInteger == NULL) { return NULL; }
    mid_IntegerConstructor = env->GetMethodID(CInteger, "<init>", "(I)V");
    if(mid_IntegerConstructor == NULL) { return NULL; }
    dataValue = env->NewObject(CInteger, mid_IntegerConstructor, *(long*)data);
                   env->DeleteLocalRef((jobject)CInteger);
    break;
    // string values
    case REG_SZ:
    szField = "REG_SZ";
    dataValue = env->NewStringUTF(data);
    break;
    // expanded environment variable values
    case REG_EXPAND_SZ:
    szField = "REG_EXPAND_SZ";
    // determine required size
    required = ExpandEnvironmentStrings(data, NULL, 0);
    tmp = (char*)malloc(required);
    // expand the strings
    if(!ExpandEnvironmentStrings(data, tmp, required)) {
    env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Error expanding registry strings");
    } // if
    dataValue = env->NewStringUTF(tmp);
              //     free(tmp); // gonx
              //     free((jobject)required);// gonx
    break;
    // string arrays (unsupported)
    case REG_MULTI_SZ:
    szField = "REG_MULTI_SZ";
    env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Unsupported data type");
    break;
    // everything else (nothing)
    default:
    env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Unsupported data type");
    break;
    } // switch
    // look up ValueType class
    jclass CValueType = env->FindClass(registryDescriptor::jcd_ValueType);
    if(CValueType == NULL) { return NULL; }
    // get the appropriate ValueType
    jfieldID fid_type = env->GetStaticFieldID(CValueType, szField, registryDescriptor::jfd_ValueType);
    if(fid_type == NULL) { return NULL; }
    jobject typeValue = env->GetStaticObjectField(CValueType, fid_type);
    // create a new RegistryValue object:
    // get RegistryValue class definition
    jclass CRegistryValue = env->FindClass(registryDescriptor::jcd_RegistryValue);
    if(CRegistryValue == NULL) { return NULL; }
    // use default constructor to create new RegistryValue
    jmethodID mid_Constructor = env->GetMethodID(CRegistryValue, "<init>", "()V");
    if(mid_Constructor == NULL) { return NULL; }
    jobject registryValue = env->NewObject(CRegistryValue, mid_Constructor);
    // use RegistryValue.setName() to set the name
    jmethodID mid_setName = env->GetMethodID(CRegistryValue, "setName", "(Ljava/lang/String;)V");
    if(mid_setName == NULL) { return NULL; }
    env->CallObjectMethod(registryValue, mid_setName, name);
    // use RegistryValue.setType() to set the type
    jmethodID mid_setType = env->GetMethodID(CRegistryValue, "setType", "(Lca/beq/util/win32/registry/ValueType;)V");
    if(mid_setType == NULL) { return NULL; }
    env->CallObjectMethod(registryValue, mid_setType, typeValue);
    // use RegistryValue.setData() to set the data
    jmethodID mid_setData = env->GetMethodID(CRegistryValue, "setData", "(Ljava/lang/Object;)V");
    if(mid_setData == NULL) { return NULL; }
    env->CallObjectMethod(registryValue, mid_setData, dataValue);
    return registryValue;
    } // else

    First thing I would do is post the code in a formatted code block. :)
    JNIEXPORT jobject JNICALL Java_ca_beq_util_win32_registry_RegistryKey_getValue(JNIEnv *env, jobject obj, jstring name) {
        // get the root key (RootKey) from the RegistryKey (this.getRootKey.getValue())
        int nRootKey = getRootKey(env, obj);
        // get the path (String) from the RegistryKey (this.getPath())
        // get reference to RegistryKey class
        jclass CRegistryKey = env->GetObjectClass(obj);
        // get field ID of path string
        jfieldID fid_path = env->GetFieldID(CRegistryKey, "path", fieldDescriptor::jfd_String);
        if (fid_path == NULL) {
            return NULL;
        // get reference to path string
        jstring path = (jstring)env->GetObjectField(obj, fid_path);
        if (path == NULL) {
            return NULL;
        // convert to native string
        const char *szPath = env->GetStringUTFChars(path, NULL);
        if (szPath == NULL) {
            return NULL;
        // open registry key for reading
        HKEY hkey;
        if (RegOpenKeyEx((HKEY)nRootKey, szPath, 0, KEY_READ, &hkey) != ERROR_SUCCESS) {
            env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Error opening registry key");
            env->ReleaseStringUTFChars(path, szPath);
            return NULL;
        } // if
        else {
            const char *szName = env->GetStringUTFChars(name, NULL);
            // find the type and size of the value
            DWORD type;
            DWORD size;
            if (RegQueryValueEx(hkey, szName, NULL, &type, (LPBYTE)NULL, &size) != ERROR_SUCCESS) {
                env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Error retreiving registry value");
                RegCloseKey(hkey);
                env->ReleaseStringUTFChars(name, szName);
                return NULL;
            } // if
            // get memory to hold the value
            char *data = (char*)malloc(size);
            // read the value
            if (RegQueryValueEx(hkey, szName, NULL, &type, (LPBYTE)data, &size) != ERROR_SUCCESS) {
                env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Error retreiving registry value");
                free(data);
                RegCloseKey(hkey);
                env->ReleaseStringUTFChars(name, szName);
                return NULL;
            } // if
            RegCloseKey(hkey);
            env->ReleaseStringUTFChars(name, szName);
            char* szField; // set to string version of registry type
            jobject dataValue; // data to be passed in RegistryValue.setData()
            jclass CInteger; // java.lang.Integer for DWORD base types
            jmethodID mid_IntegerConstructor; // java.lang.Integer.Integer(int) for DWORD base types
            char *tmp; // buffer, used when expanding REG_EXPAND_SZ types
            DWORD required; // buffer size, used when expanding REG_EXPAND_SZ types
            // convert the registry data to a Java type
            switch (type) {
            // raw, unformatted, binary data
            case REG_NONE:
            case REG_BINARY:
                if (type == REG_NONE) {
                    szField = "REG_NONE";
                } // if
                else {
                    szField = "REG_BINARY";
                } // else
                dataValue = env->NewByteArray(size);
                if (dataValue == NULL) {
                    return NULL;
                env->SetByteArrayRegion((jbyteArray)dataValue, 0, size, (signed char*)data);
                break;
                // integer/long values
            case REG_DWORD:
            case REG_DWORD_BIG_ENDIAN:
                if (type == REG_DWORD) {
                    szField = "REG_DWORD";
                } // if
                else {
                    szField = "REG_DWORD_BIG_ENDIAN";
                } // else
                CInteger = env->FindClass(classDescriptor::jcd_Integer);
                if (CInteger == NULL) {
                    return NULL;
                mid_IntegerConstructor = env->GetMethodID(CInteger, "<init>", "(I)V");
                if (mid_IntegerConstructor == NULL) {
                    return NULL;
                dataValue = env->NewObject(CInteger, mid_IntegerConstructor, *(long*)data);
                env->DeleteLocalRef((jobject)CInteger);
                break;
                // string values
            case REG_SZ:
                szField = "REG_SZ";
                dataValue = env->NewStringUTF(data);
                break;
                // expanded environment variable values
            case REG_EXPAND_SZ:
                szField = "REG_EXPAND_SZ";
                // determine required size
                required = ExpandEnvironmentStrings(data, NULL, 0);
                tmp = (char*)malloc(required);
                // expand the strings
                if (!ExpandEnvironmentStrings(data, tmp, required)) {
                    env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Error expanding registry strings");
                } // if
                dataValue = env->NewStringUTF(tmp);
                // free(tmp); // gonx
                // free((jobject)required);// gonx
                break;
                // string arrays (unsupported)
            case REG_MULTI_SZ:
                szField = "REG_MULTI_SZ";
                env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Unsupported data type");
                break;
                // everything else (nothing)
            default:
                env->ThrowNew(env->FindClass(registryDescriptor::jcd_RegistryException), "Unsupported data type");
                break;
            } // switch
            // look up ValueType class
            jclass CValueType = env->FindClass(registryDescriptor::jcd_ValueType);
            if (CValueType == NULL) {
                return NULL;
            // get the appropriate ValueType
            jfieldID fid_type = env->GetStaticFieldID(CValueType, szField, registryDescriptor::jfd_ValueType);
            if (fid_type == NULL) {
                return NULL;
            jobject typeValue = env->GetStaticObjectField(CValueType, fid_type);
            // create a new RegistryValue object:
            // get RegistryValue class definition
            jclass CRegistryValue = env->FindClass(registryDescriptor::jcd_RegistryValue);
            if (CRegistryValue == NULL) {
                return NULL;
            // use default constructor to create new RegistryValue
            jmethodID mid_Constructor = env->GetMethodID(CRegistryValue, "<init>", "()V");
            if (mid_Constructor == NULL) {
                return NULL;
            jobject registryValue = env->NewObject(CRegistryValue, mid_Constructor);
            // use RegistryValue.setName() to set the name
            jmethodID mid_setName = env->GetMethodID(CRegistryValue, "setName", "(Ljava/lang/String;)V");
            if (mid_setName == NULL) {
                return NULL;
            env->CallObjectMethod(registryValue, mid_setName, name);
            // use RegistryValue.setType() to set the type
            jmethodID mid_setType = env->GetMethodID(CRegistryValue, "setType", "(Lca/beq/util/win32/registry/ValueType;)V");
            if (mid_setType == NULL) {
                return NULL;
            env->CallObjectMethod(registryValue, mid_setType, typeValue);
            // use RegistryValue.setData() to set the data
            jmethodID mid_setData = env->GetMethodID(CRegistryValue, "setData", "(Ljava/lang/Object;)V");
            if (mid_setData == NULL) {
                return NULL;
            env->CallObjectMethod(registryValue, mid_setData, dataValue);
            return registryValue;
        } // else
    }

  • Memory Leaks in JNI code

    Hi,
    I have written a small C++ code which will load a JDBC Driver and connect to the database.
    The code initially Loads the JVM & than connects to the Database.
    When i tested the code with Boundscheket I found a conciderable amount of memory leak & all of these are shown in jvm.dll, zip.dll & java.dll. Is this OK? Are there memory leaks in JNI?

    Hi, Please go through the code & let me know if there are any memory leaks in this code. Boundchecker detects a considerable amount of memory leak :(
    #include <windows.h>
    #include <stdio.h>
    #include <jni.h>
    #include <conio.h>
    #define INI_MAX_PROPERTY_VALUE 1024
    #define JVMPATH "C:\\Java\\jdk1.5\\jre\\bin\\client\\jvm.dll"
    #define JDBCDRIVER "-Djava.class.path=D:\\mysql-connector-java.jar";
    #define CONNECTIONSTRING "jdbc:mysql://localhost:3306/test?user=root&password=root"
    #define DRIVERCLASS "com/mysql/jdbc/Driver"
    JavaVM *jvm = NULL;
    unsigned long int jvmVersion = 0x00010004;
    HINSTANCE lib_handle = NULL;
    void fini() {
         jint res = jvm->DestroyJavaVM();
         printf ("Destroying JVM %d\n",res);
         if (lib_handle) {
              FreeLibrary(lib_handle);
              printf ("Deleted lib handle\n");
    void init()
         char jvmPath[INI_MAX_PROPERTY_VALUE + 1];
         jint res = -1;
         JNIEnv *jniEnv = NULL;
         JavaVMInitArgs vm_args;
         JavaVMOption options[1];
         options[0].optionString = JDBCDRIVER;
         vm_args.version = jvmVersion;
    vm_args.options = options;
    vm_args.nOptions = 1;
    vm_args.ignoreUnrecognized = JNI_TRUE;
         memset(jvmPath, '\0', INI_MAX_PROPERTY_VALUE + 1);
         strcpy(jvmPath,JVMPATH);
         printf("Loading dll from %s\n",jvmPath);
         lib_handle = LoadLibrary(jvmPath);
         if (!lib_handle)
              printf("Error during LoadLibrary\n");
              return;
         printf("JVM dll Loaded Sucessfully\n");
         jint (__stdcall JNI_CreateJavaVM)( JavaVM*, void**, void*);
         JNI_CreateJavaVM = (jint (__stdcall *)(JavaVM**, void**, void*))GetProcAddress(lib_handle, "JNI_CreateJavaVM");
         if (NULL != JNI_CreateJavaVM)
              res = (JNI_CreateJavaVM)( &jvm, (void**)&jniEnv , &vm_args);
         if ( res < 0 ) {
              printf("Unable to create JVM\n");
         } else {
              printf("JVM Created Succesfully\n");
    void printException(JNIEnv *jniEnv) {
         jthrowable exceptionHandle = jniEnv->ExceptionOccurred();
         if ( exceptionHandle == NULL )
              return;
         /* Clear the exception from the enviroment*/
         jniEnv->ExceptionClear();
         /* Obtain the JavaException object to get its details */
         jclass jThrowableClass = jniEnv->GetObjectClass(exceptionHandle);
         if ( jThrowableClass == NULL ) {
              if (exceptionHandle)
                   jniEnv->DeleteLocalRef(exceptionHandle);     
              exceptionHandle = NULL;
              return ;
         printf("\n*****----- Java Error Message is -----*****\n");
         jmethodID midMessage = jniEnv->GetMethodID( jThrowableClass, "toString", "()Ljava/lang/String;" );
         if ( midMessage == NULL ){
              if (exceptionHandle)
                   jniEnv->DeleteLocalRef(exceptionHandle);
              if (jThrowableClass)
                   jniEnv->DeleteLocalRef(jThrowableClass);
              exceptionHandle = NULL;
              jThrowableClass = NULL;
              return;
         jstring jstrRet = (jstring)jniEnv->CallObjectMethod(exceptionHandle,midMessage);
         if ( jstrRet == NULL ){
              if (exceptionHandle)
                   jniEnv->DeleteLocalRef(exceptionHandle);
              if (jThrowableClass)
                   jniEnv->DeleteLocalRef(jThrowableClass);
              exceptionHandle = NULL;
              jThrowableClass = NULL;
              return;
         jboolean flg;
         const char *pExceptionStr = jniEnv->GetStringUTFChars(jstrRet, &flg);
         if ( flg == JNI_TRUE ) {
              printf("%s",pExceptionStr);
              jniEnv->ReleaseStringUTFChars(jstrRet, pExceptionStr);
         if (exceptionHandle)
              jniEnv->DeleteLocalRef(exceptionHandle);
         if (jThrowableClass)
              jniEnv->DeleteLocalRef(jThrowableClass);
         if (jstrRet)
              jniEnv->DeleteLocalRef(jstrRet);
         exceptionHandle = NULL;
         jThrowableClass = NULL;
         jstrRet = NULL;
         printf("\n**************---------End of Java Error Message ************\n");
         return;
    void connect() {
         jint res = -1;
         JNIEnv *jniEnv = NULL;
         jclass clsDriver = NULL;
         jmethodID colnstructorDriver = NULL;
         jmethodID methodConnect = NULL;
         jobject objectDriver = NULL;
         jobject objectConnection = NULL;
         jstring jConnectionString = NULL;
         printf("Getting the Enviroment\n");
         jint isPresent = jvm->GetEnv((void **)&jniEnv, jvmVersion );
         if (isPresent == JNI_EDETACHED || jniEnv == NULL) {
              printf("Could not get JNI Env for current thread");
    return;
         printf("Creating Instance of Driver\n");
         clsDriver = jniEnv->FindClass(DRIVERCLASS);
         colnstructorDriver = jniEnv->GetMethodID(clsDriver, "<init>", "()V");
         objectDriver = jniEnv->NewObject( clsDriver, colnstructorDriver );
         printf("Created Instance of Driver\n");
         printf("Connecting to the Database\n");
         methodConnect = jniEnv->GetMethodID(clsDriver, "connect", "(Ljava/lang/String;Ljava/util/Properties;)Ljava/sql/Connection;");
         jConnectionString = jniEnv->NewStringUTF(CONNECTIONSTRING);
         objectConnection = jniEnv->CallObjectMethod(objectDriver, methodConnect, jConnectionString, NULL);
         if (objectConnection == NULL) {
              printException(jniEnv);
              printf("Unable to Connect\n");
         else
              printf("Connection Done\n");
         //Releasing all the memory used....
         if (objectConnection)
              jniEnv->DeleteLocalRef(objectConnection);
         if (jConnectionString)
              jniEnv->DeleteLocalRef(jConnectionString);
         if (objectDriver)
              jniEnv->DeleteLocalRef(objectDriver);
         if (clsDriver)
              jniEnv->DeleteLocalRef(clsDriver);
         objectConnection = NULL;
         jConnectionString = NULL;
         objectDriver = NULL;
         clsDriver = NULL;
    int main() {
         printf ("Starting...\n");
         init();
         connect();
         fini();
         getch();
    }

  • Problem executing jni code

    I'm working with jni for java and c in fedora core. I could compile sucessfully but at the last step while executiton it is giving the follwing error
    Exception in thread "main" java.lang.UnsatisfiedLinkError: no HelloNative in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1517)
    at java.lang.Runtime.loadLibrary0(Runtime.java:788)
    at java.lang.System.loadLibrary(System.java:834)
    at HelloNative.<clinit>(HelloNative.java:6)
    at HelloNativeTest.main(HelloNativeTest.java:5)
    I also setted my path variable
    LD_LIBRARY_PATH=`pwd`
    export LD_LIBRARY_PATH
    but still not working how to solve the problem. Please help me in this aspect.
    Waiting for your responce.

    HI,
    Thank you. These are all the files present in the current directory. But still is is not working. I couldnt understand the cause.
    HelloNative.cc HelloNative.java HelloNativeTest.java
    HelloNative.class HelloNative.so
    HelloNative.h HelloNativeTest.class
    This is the code for HelloNative.cc which compiled well and given the output file HelloNative.cc
    # include "HelloNative.h"
    # include <stdio.h>
    #include <jni.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <sys/mman.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <unistd.h>
    JNIEXPORT void JNICALL Java_HelloNative_greeting
    (JNIEnv * env, jclass c1)
    printf("Hello world!");
    this is the code for HelloNative.java
    public class HelloNative
    public native static void greeting();
    static
    System.loadLibrary("HelloNative");
    Then what is the problem i couldnt understand

  • Can a applet call a JNI code

    I need to develop a browser plugin or analogus plugin utility which will download from the server and and then make a local DLL call. the local DLL call includes starting a Windows exe system which will start another software (pre-installed on the client system) in another process.
    I searched around with the NPAPI plugin and FireBreath frameworks. But my biggest drawback is i am novice in C++.
    Can I make an applet will make a JNI call to call the windows systems dll. I know a signed applet can use the System.load function (excuse me if i am syntactically wrong) but i am not sure if it can start a exe or make a JNI call.
    As i have no time to learn and code in C++ the applet path seems to be the most viable one.
    Please suggest
    Vishwanath

    vwashimkar wrote:
    As i have no time to learn and code in C++ the applet path seems to be the most viable one.
    Please suggestThen you are out of luck.
    I suspect you think that you can use java to directly call your dll. That won't happen.
    Closest you can get to that is JNA (3rd party library "Java Native Access") and using that requires that you learn JNA and unless your dll has a simple interface figuring out how to use JNA will likely require some knowledge of C/C++ and calling semantics.

Maybe you are looking for