Native - Java Method Call problem - "Wrong Method ID..."

I am writing a 3d game engine using c++, with all the game logic code in Java, for the purpose of making the thing extendible, easily modifyable, etc...
I am using J2SE JDK 1.2.2.
Most things work fine (engine-wise), but i have a few questions about problems i am having getting the JNI to work correctly with calls to Java Methods.
1. If I use FindClass() to get a jclass reference to a named class, I get one number back. If I then instantiate this class, and then call GetObjectClass() with the instance, I get another number, **which doesnt appear to work for anything**. What is going on here? Can the JVM give different jclass numbers for the same class? Is GetObjectClass() supposed to work?
2. Is AllocObject() alright for instantiating Java objects? It does seem to allocate memory, and method calls work to the new object. I am aware that it doesn't call a constructor, but I like that, seeing as the initialization is handled through a different [network-synchronized] means.
3. Using a jclass retrieved using FindClass(), which I store in a global variable, I am able to call methods on an instance that I created in a certain function. I then make sure (?) that the GC can't reclaim the class or object memory by getting a NewGlobalReference to both of them [just to be safe]. However, in a later function, I am unable to call methods using my stored method IDs, ["Wrong Method ID....JVM has been asked to shut down this application in an unusual manner..."]. I am also unable to acquire new methodIDs, as the system returns 0xCCCCCCCC for all method ID queries. Obviously, attempting to use those bogus method IDs results in a JVM crash, in a segment called [2 deep in the untraceable depths of JVM.dll] from the JNI CallVoidMethodV() function. Why is this happening? Is the GC getting in there despite my best efforts? Is it illegal to cache methodIDs, jclass references or jobject references? aaarrggh! :)
Thanks
Chris Forbes
Lead Programmer
Sprocket Interactive
[email protected]

Hi Chris,
I hit the same sort of problem, when writing a JVMDI ( VM debugger hook ), in C++.
My question remained unanswered too
http://forum.java.sun.com/thread.jsp?forum=47&thread=461503&tstart=30&trange=30
I didn't try a call to NewGlobalRef, as you did... but it sounds like it could be what I was missing.
I've a couple of ideas, but nothing definite for you.
1) maybe there's more than one classloader, so that multiple copies of the class are loaded
2) ensure you're compiling your DLL with "quad-word" ( 8 byte ) alignment.
Otherwise all your JNI references will be misaligned !
Since the JNI reference maps to a C++ pointer, it's possible that you can't cache any JNI references.
That's my vague feeling on the subject.
As a workaround, you may have to keep requesting any JNI references, eg. jclass & jmethod's, as you need them.
regards,
Owen

Similar Messages

  • Problem calling a Java Method from C++

    hi everyone,
    i'm using JNI and i'm trying to call a Java method from C++, this is the code:
    SocketC.java
    public class SocketC
    private native void conectaServidor();
    private void recibeBuffer()
    System.out.println("HELLO!!!");
    public static void main(String args[])
    SocketC SC = new SocketC();
    SC.conectaServidor();
    static {
    System.loadLibrary("Server_TCP");
    Server_TCP.cpp
    char* recibirSock()
         int _flag = 1;
         while(_flag != 0)
              memset(buffer,0,sizeof(buffer));//Et la, celle pour recevoir
              recv(sock,buffer,sizeof(buffer),0);
              printf(" Mensaje del cliente: %s\n",buffer);
              _flag = strcmp(buffer,"salir");
         }//fin while
         return buffer;
    void enviarSock()
         int _flag = 1;
         getchar();
         while(_flag != 0)
              memset(buffer,0,sizeof(buffer));//procedimiento para enviar
              printf("\n Escriba: ");
              gets(buffer);
         //     err=scanf("%s",buffer);
              send(sock,buffer,sizeof(buffer),0);
              _flag = strcmp(buffer,"salir");
         }//fin while
    }//fin enviarSock
    DWORD servicio(LPVOID lpvoid)//
         char *buf;
         printf("\n Cliente aceptado!!!!!\n");
         buf=recibirSock();
         return 0;
    JNIEXPORT void JNICALL Java_SocketC_conectaServidor(JNIEnv *env, jobject obj)
    //void main()
    /*this is the problem i'm calling the method recibeBuffer*/
         jclass cls = env->GetObjectClass(obj);
         jmethodID mmid = env->GetMethodID(cls, "recibeBuffer", "(V)V");
         if (mmid == 0)
              return;
         env->CallVoidMethod(obj, mmid); //llama a Java
         WSAStartup(MAKEWORD(2,0),&wsa);//MAKEWORD dit qu'on utilise la version 2 de winsock
         printf("TCP conexion Sockets\n\n");
         //estimez vous heureux que je foute pas de copyright ;)
         system("TITLE TCP Conexion Sockets (Version server)");
         //fo avouer que c'est plus joli
         int port;
         printf("Port : ");//On demande juste le port, pas besoin d'ip on est sur un server
         scanf("%i",&port);
         sinserv.sin_family=AF_INET;     //Je ne connais pas d'autres familles
         sinserv.sin_addr.s_addr=INADDR_ANY;//Pas besoin d'ip pour le server
         sinserv.sin_port=htons(port);
         server=socket(AF_INET,SOCK_STREAM,0);//On construit le server
         //SOCK_STREAM pour le TCP
         bind(server,(SOCKADDR*)&sinserv,sizeof(sinserv));
         //On lie les parametres du socket avec le socket lui meme
         listen(server,SOMAXCONN);//On se met � �couter avec server, 0 pour n'accepter qu'une seule connection
         printf(" Servidor conectado.");
         while(1)
              sinsize=sizeof(sin);
              if((sock=accept(server,(SOCKADDR*)&sin,&sinsize))!=INVALID_SOCKET)
              {//accept : acepta cualquier conexion
                   if (hReadThread = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)
                   servicio, 0, 0, &dwThreadID))
                        printf("\nHOLA!");
                        GetExitCodeThread(hReadThread,&dwExitCode);
                        CloseHandle (hReadThread);
                   else
                        // Could not create the read thread.
                        printf("No se pudo crear");
                        exit(0);
    when i'm running the proyect i get this error:
    C:\POT Files\UCAB\tesis\esmart\french>java SocketC
    Exception in thread "main" java.lang.NoSuchMethodError: recibeBuffer
    at SocketC.conectaServidor(Native Method)
    at SocketC.main(SocketC.java:16)
    i don't know why this is happening i got declare the method recibeBuffer in my SocketC.java class, but doesn;t work can anyone help me?
    PD: sorry for my bad english i'm from Venezuela

    Next time please paste your code between [code] tags with the code button just above the edit message area.
    To answer your question, you wrote the wrong method signature. It should be:jmethodID mmid = env->GetMethodID(cls, "recibeBuffer", "()V");Regards

  • FATAL ERROR in native method: Wrong method ID used to invoke a Java method

    When calling the same method second time , I get message ::
    <FATAL ERROR in native method: Wrong method ID used to invoke a Java method>
    void myFunction(int myVal)
    JNIEnv *env = NULL;
    jclass odbcconnls;
    jint res;
    printf("\nInitilaizing class ");
    res = (jvm)->AttachCurrentThread((void **)&env,NULL);
    if (res < 0) {
    fprintf(stderr, "Can't get Env \n");
    (jvm)->DestroyJavaVM();
    return SQL_ERROR;          
    if(res == JNI_OK)
    printf("\nThe env is initialized ");
    if(*(&env) == NULL)
    printf(" the env is NULL ");
    printf("\nenv :::::: %s ", env);     
    // the jobject (dbc->actualConn) is a global reference
    odbcconnls = (env)->GetObjectClass(dbc->actualConn);
    if (odbcconnls == NULL) {
    goto destroy;
    switch(myVal){
    case 1:
    jmethodID methodId ;
    jboolean jbool;
    SQLINTEGER Val = (SQLINTEGER )Value;
    SQLINTEGER val1 = *Val;
    methodId = (env)->GetMethodID( odbcconnls,"myFun1","(Z)V");
    if(methodId == NULL){
    goto destroy;
    if(val1 == SQL_FALSE )
    jbool = 0;
    else
    jbool =1;
    env->CallVoidMethod(dbc->actualConn,methodId,jbool);
    env->DeleteLocalRef((jobject)res);
    env->DeleteLocalRef((jobject)odbcconnls);
    env->DeleteLocalRef((jobject)methodId);
    jvm->DetachCurrentThread();
    return ;
    case 2 :
    jmethodID methodId1 ;
    SQLUINTEGER* Level;
    methodId1 = (env)->GetMethodID( odbcconnls,"myFun2","(I)V");
    if(methodId1 == NULL){
    goto destroy;
    Level = (SQLUINTEGER *)Value;
    env->CallVoidMethod(dbc->actualConn,methodId1,(int)*Level);
    dbc->txn_isolation = (SQLUINTEGER)Value;
    env->DeleteLocalRef((jobject)res);
    env->DeleteLocalRef((jobject)odbcconnls);
    env->DeleteLocalRef((jobject)methodId1);
    jvm->DetachCurrentThread();
    return ;
    case 3 :
    SQLCHAR* Cate;
    jmethodID methodId2 ;
    jstring jStrCat;
    methodId2 = (env)->GetMethodID(odbcconnls,"myFun3","(Ljava/lang/String;)V");
    if(methodId2 == NULL){
    goto destroy;
    Cate = new SQLCHAR[20];
    strcpy((char *)CCatalog,(char *)Value);
    jStrCat = env->NewStringUTF((char *) Cate);
    printf("\n got jSTring ");
    env->CallVoidMethod(dbc->actualConn,methodId2,jStrCat);
    printf("\n after called method ");
    int len = strlen((char *)Cate);
    dbc->Cate = new SQLCHAR[len+1];
    strcpy((char *)dbc->Cate,(char *)Cate);
    printf("\n copied result ");
    env->DeleteLocalRef((jobject)res);
    env->DeleteLocalRef((jobject)odbcconnls);
    env->DeleteLocalRef((jobject)methodId2);
    jvm->DetachCurrentThread();
    return ;
    destroy:
    if ((env)->ExceptionOccurred()) {
    (env)->ExceptionDescribe();
    jvm->DetachCurrentThread();
    (jvm)->DestroyJavaVM();
    return SQL_ERROR;
    When case 1 is called second time this error is thrown..
    plz help me..
    Thanx
    MittalSunita.

    When calling the same method second time , I get
    message ::
    <FATAL ERROR in native method: Wrong method ID used
    d to invoke a Java method>
    void myFunction(int myVal)
    JNIEnv *env = NULL;
    jclass odbcconnls;
    jint res;
    printf("\nInitilaizing class ");
    res = (jvm)->AttachCurrentThread((void **)&env,NULL);
    if (res < 0) {
    fprintf(stderr, "Can't get Env \n");
    (jvm)->DestroyJavaVM();
    return SQL_ERROR;          
    if(res == JNI_OK)
    printf("\nThe env is initialized ");
    if(*(&env) == NULL)
    printf(" the env is NULL ");
    printf("\nenv :::::: %s ", env);     
    // the jobject (dbc->actualConn) is a global
    reference
    odbcconnls = (env)->GetObjectClass(dbc->actualConn);
    if (odbcconnls == NULL) {
    goto destroy;
    switch(myVal){
    case 1:
    jmethodID methodId ;
    jboolean jbool;
    SQLINTEGER Val = (SQLINTEGER )Value;
    SQLINTEGER val1 = *Val;
    methodId = (env)->GetMethodID(
    ( odbcconnls,"myFun1","(Z)V");
    if(methodId == NULL){
    goto destroy;
    if(val1 == SQL_FALSE )
    jbool = 0;
    else
    jbool =1;
    env->CallVoidMethod(dbc->actualConn,methodId,jbool);
    env->DeleteLocalRef((jobject)res);
    env->DeleteLocalRef((jobject)odbcconnls);
    env->DeleteLocalRef((jobject)methodId);
    jvm->DetachCurrentThread();
    return ;Why do you delete a local reference???
    Did you ever call the get local reference?
    case 2 :
    jmethodID methodId1 ;
    SQLUINTEGER* Level;
    methodId1 = (env)->GetMethodID(
    ( odbcconnls,"myFun2","(I)V");
    if(methodId1 == NULL){
    goto destroy;
    Level = (SQLUINTEGER *)Value;
    env->CallVoidMethod(dbc->actualConn,methodId1,(int)*Le
    el);
    dbc->txn_isolation = (SQLUINTEGER)Value;
    env->DeleteLocalRef((jobject)res);
    env->DeleteLocalRef((jobject)odbcconnls);
    env->DeleteLocalRef((jobject)methodId1);
    jvm->DetachCurrentThread();
    return ;
    case 3 :
    SQLCHAR* Cate;
    jmethodID methodId2 ;
    jstring jStrCat;
    methodId2 =
    (env)->GetMethodID(odbcconnls,"myFun3","(Ljava/lang/St
    ing;)V");
    if(methodId2 == NULL){
    goto destroy;
    Cate = new SQLCHAR[20];
    strcpy((char *)CCatalog,(char *)Value);
    jStrCat = env->NewStringUTF((char *) Cate);
    printf("\n got jSTring ");
    env->CallVoidMethod(dbc->actualConn,methodId2,jStrCat)
    printf("\n after called method ");
    int len = strlen((char *)Cate);
    dbc->Cate = new SQLCHAR[len+1];
    strcpy((char *)dbc->Cate,(char *)Cate);
    printf("\n copied result ");
    env->DeleteLocalRef((jobject)res);
    env->DeleteLocalRef((jobject)odbcconnls);
    env->DeleteLocalRef((jobject)methodId2);
    jvm->DetachCurrentThread();
    return ;
    destroy:
    if ((env)->ExceptionOccurred()) {
    (env)->ExceptionDescribe();
    jvm->DetachCurrentThread();
    (jvm)->DestroyJavaVM();
    return SQL_ERROR;
    When case 1 is called second time this error is
    thrown..
    plz help me..
    Thanx
    MittalSunita.

  • Problem calling java method from c

    Hi ,
    I'm trying to call a java method from a C program. it gives no error during compilation as well as building the application. but when i tried to create the JVM by running my application it pops up the message "The application failed to start because jvm.dll was not found. Re-installing the application may fix the problem." I tried out setting all the environment variables to include the jvm.dll(PATH set to c:\j2sdk1.4.2_05\bin;c:\j2sdk1.4.2_05\jre\bin). Still got the same message. Then i re-installed java platform once more. Even now i get the same error. I have more than one jvm.dll at locations jre\bin\client and server, oracle has some jvm.dll . Will that be a problem? if so can i remove those? which of them should be removed and how?
    The code i'm using is
    #include <stdio.h>
    #include <jni.h>
    #include <windows.h>
    //#pragma comment (lib,"C:\\j2sdk1.4.2_05\\lib\\jvm.lib")
    JavaVM jvm; / Pointer to a Java VM */
    JNIEnv env; / Pointer to native method interface */
    JDK1_1InitArgs vm_args; /* JDK 1.1 VM initialization requirements */
    int verbose = 1; /* Debugging flag */
    FARPROC JNU_FindCreateJavaVM(char *vmlibpath)
    HINSTANCE hVM = LoadLibrary("jre\\bin\\server\\jvm.dll");
    if (hVM == NULL)
    return NULL;
    return GetProcAddress(hVM, "JNI_CreateJavaVM");
    void main(int argc, char **argv )
    JavaVM jvm = (JavaVM )0;
    JNIEnv env = (JNIEnv )0;
    JavaVMInitArgs vm_args;
    jclass cls;
    jmethodID mid;
    jint res;
    FARPROC pfnCreateVM;
    JavaVMOption options[4];
    // jint (__stdcall pfnCreateVM)(JavaVM *pvm, void **penv, void *args) = NULL;
    options[0].optionString = "-Djava.compiler=NONE"; /* disable JIT */
    options[1].optionString = "-Djava.class.path=c:/j2sdk1.4.2_05/jre/lib/rt.jar"; /* user classes */
    options[2].optionString = "-Djava.library.path=lib"; /* set native library path */
    options[3].optionString = "-verbose:jni"; /* print JNI-related messages */
    /* Setup the environment */
    vm_args.version = JNI_VERSION_1_4;
    vm_args.options = options;
    vm_args.nOptions = 4;
    vm_args.ignoreUnrecognized = 1;
    JNI_GetDefaultJavaVMInitArgs ( &vm_args );
    pfnCreateVM = JNU_FindCreateJavaVM("jre\\bin\\server\\jvm.dll");
    res = (*pfnCreateVM)(&jvm,(void **) &env, &vm_args );
    // res = JNI_CreateJavaVM(&jvm,(void **) &env, &vm_args );
    /* Find the class we want to load */
    cls = (*env)->FindClass( env, "InstantiatedFromC" );
    if ( verbose )
    printf ( "Class: %x" , cls );
    /*jvm->DestroyJavaVM( );*/
    Could anyone help me solve this problem as early as possible, bcoz i'm in an urge to complete the project.
    Thanks in advance.
    Usha.

    You either have to add to the system path of where is your jvm.dll is located or explicitly link to jvm.dll call GetProcAddress to obtain the address of an exported function in the DLL.

  • Problem with OSB 11g - Unable to call non-static java methods

    I have a problem in OSB. Unable to see any java methods when loading java callout. I have checked the java classes in the .jar file and they are all non-static java methods.
    Is there any way where OSB is able to see this non-static java methods?
    Need help urgently!
    Thanks!

    Technical standpoint: Do you know why OSB is not able to call non-static methods?
    This is by design. Ability to call non-static methods require Object creation which adds additional complexity. eg How to pass variables in constructor?. How/where to store created object for use across across pipeline instance?. Object life cycle (when and how to create object) etc. To avoid above complexites static methods are only supported.
    "a lot of non-static method to call" just for my understanding what are the number involved?. If number is too high you can always request for a enhancement.
    Thanks
    Manoj

  • Problem calling Java method from JavaScript in JSP / ADF

    Hi all,
    In my JavaScript onMouseUp() function, I need to call a method on my Java backing bean. How is this done? Info on the web indicates a static Java method can be called by simply "package.class.staticMethod(...)". but when I put the statement
    "jsf.backing.GlobalRetriever.createBasemap(affectedLayer);"
    I get an error message "jsf is undefined".
    The functionality I'm trying to get is: I have a custom slider control and based on its value, I want to call oracle map viewer specifying a map extent of the (current extent / slider value) to do a zoom in/out. In addition, the slider uses a onMouseMove() function to change the size of the image display so it looks like a dynamic zoom in/out.
    Please assist or let me know if I can provide some additional information. Thanks in advance.
    Jim Greetham

    No. The Java and Javascript in a Faces application are really working in two different universes.
    Java is running on the server. It generates HTML (and sometimes even Javascript) and sends that to the client machine. That's where all your backing beans are.
    Javascript runs directly in the browser. There's no way anything on the server can have access to anything you define in Javascript, unless you explicitly send that information back to the server, either via standard form submission (which only works when someone presses a "Submit" button) or via an Ajax-type call. So otherwise, nothing you define in Javascript will ever be available to a backing bean.

  • Order of arguments while calling a Java method from C

    Hi
    are there any rules to order the transferred arguments ?
    I wanted to transfer a native window event from C to Java and if the called
    java method is declared like this: (int, long, int) (IJI)V
    public static void nativeMouseButtonDownCallback(int wParam, long lParam, int which)
    the value of 'which' is not correct (always the same independent from what I set it to in the C function)
    If I declare the java method like this: (int, int, long) (IIJ)V
    public static void nativeMouseButtonDownCallback(int which, int wParam, long lParam)
    everything is fine.
    Any information appreciated !
    Bye Mark

    Thanks for your reply !
    Initially I also thought that the set of the value could be wrong and so
    I used a printf statement in C to monitor the transferred value.
    And still: the value I put in was different from what I got in java.
    After this I put in simple numbers like 1,2,3 and in java I still got
    the same wrong value.(guess max signed int 21474836..)
    I really replaced the dll and class files and restarted the IDE.
    The problem got solved by changing the order of the long an int.
    Bye Mark

  • How to call a Java method in a C consoleapplication?

    I have to call a void method of a javaclass using a c consoleapplication. No argument are passed to it.
    I can't make an object of that class..
    This is my implementation in c (using JNI):
    void update(void)
         classn = "<name>";
         cls = (*env) ->FindClass(env, classn );
         if (cls == 0)
    printf(" Can't find class %s\n", classn );
         mid =
    (*env)->GetMethodID(env, cls, "<methodname>", "()V");
         (*env)->CallVoidMethod(obj, env ,m id);
    This goes wrong...
    The problem is that I have no jobject (obj) of the class, because I don't want one...I don't need one. How can I call that void method without an object and only using the classname..??

    You have to make the java method a static method, and use CallStaticVoidMethod.
    "static" means that the method belongs to the class, and not an object of that class.

  • Java method call from c passing string more info

    I am trying to call a java method from c passing a String as an argument.
    my C code is as follows.
    //Initalise jstring and class (to recieve String)
    jstring textp;
    jclass texts = (*env)->GetObjectClass(env, obj);
    jmethodID text = (*env)->GetMethodID(env, texts, "texture", "([Ljava/lang/String;)V");
    //Create a new jstring from the char* texturePath (in textures)
    //call the java method with the jstring
    textp = (*env)->NewStringUTF(env,ret.textures->texturePath);
    (*env)->CallVoidMethod(env, obj, text,textp);
    //java code
    // texture which recieves a string
    public void texture(String texturePath){
    The error I get is as follows:
    SIGSEGV 11 segmentation violation
    si_signo [11]: SEGV
    si_errno [0]:
    si_code [1]: SEGV_MAPERR [addr: 0xc]
    stackpointer=FFBED790
    "Screen Updater" (TID:0x4f9060, sys_thread_t:0x4f8f98, state:CW, thread_t: t@11, threadID:0xf2d31d78, stack_bottom:0xf2d32000, stack_size:0x20000) prio=4
    [1] java.lang.Object.wait(Object.java:424)
    [2] sun.awt.ScreenUpdater.nextEntry(ScreenUpdater.java:78)
    [3] sun.awt.ScreenUpdater.run(ScreenUpdater.java:98)
    "AWT-Motif" (TID:0x40be50, sys_thread_t:0x40bd88, state:R, thread_t: t@10, threadID:0xf2d71d78, stack_bottom:0xf2d72000, stack_size:0x20000) prio=5
    [1] sun.awt.motif.MToolkit.run(Native Method)
    [2] java.lang.Thread.run(Thread.java:479)
    "SunToolkit.PostEventQueue-0" (TID:0x431950, sys_thread_t:0x431888, state:CW, thread_t: t@9, threadID:0xf2e71d78, stack_bottom:0xf2e72000, stack_size:0x20000) prio=5
    [1] java.lang.Object.wait(Object.java:424)
    [2] sun.awt.PostEventQueue.run(SunToolkit.java:407)
    "AWT-EventQueue-0" (TID:0x430ea8, sys_thread_t:0x430de0, state:CW, thread_t: t@8, threadID:0xf3071d78, stack_bottom:0xf3072000, stack_size:0x20000) prio=6
    [1] java.lang.Object.wait(Object.java:424)
    [2] java.awt.EventQueue.getNextEvent(EventQueue.java:212)
    [3] java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:100)
    [4] java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:91)
    [5] java.awt.EventDispatchThread.run(EventDispatchThread.java:83)
    Exiting Thread (sys_thread_t:0xff343db0) : no stack
    "Finalizer" (TID:0x154e98, sys_thread_t:0x154dd0, state:CW, thread_t: t@6, threadID:0xfe391d78, stack_bottom:0xfe392000, stack_size:0x20000) prio=8
    [1] java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:146)
    [2] java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:168)
    [3] java.lang.ref.Finalizer$FinalizerWorker$FinalizerThread.run(Finalizer.java:124)
    "Reference Handler" (TID:0x1506a0, sys_thread_t:0x1505d8, state:CW, thread_t: t@5, threadID:0xfe3c1d78, stack_bottom:0xfe3c2000, stack_size:0x20000) prio=10
    [1] java.lang.Object.wait(Object.java:424)
    [2] java.lang.ref.Reference$ReferenceHandler.run(Reference.java:130)
    "Signal dispatcher" (TID:0x13d180, sys_thread_t:0x13d0b8, state:MW, thread_t: t@4, threadID:0xfe3f1d78, stack_bottom:0xfe3f2000, stack_size:0x20000) prio=10
    "main" (TID:0x38918, sys_thread_t:0x38850, state:R, thread_t: t@1, threadID:0x25228, stack_bottom:0xffbf0000, stack_size:0x800000) prio=5 *current thread*
    [1] loader.Callbacks.nativeMethod(Native Method)
    [2] loader.Callbacks.main(Callbacks.java:184)
    [3] graphics.GR_MakeTrack.init(GR_MakeTrack.java:60)
    [4] graphics.GR_MakeTrack.main2(GR_MakeTrack.java:49)
    [5] graphics.GR_MakeTrack.main(GR_MakeTrack.java:41)
    [6] control.GE_main.GE_main1(GE_main.java:87)
    [7] control.GE_main.main(GE_main.java:66)
    gmake: *** [run] Abort (core dumped)

    I am trying to call a java method from c passing a
    String as an argument.
    my C code is as follows.
    //Initalise jstring and class (to recieve String)
    jstring textp;
    jclass texts = (*env)->GetObjectClass(env, obj);
    jmethodID text = (*env)->GetMethodID(env, texts,
    "texture", "([Ljava/lang/String;)V");
    Hi Pete,
    your problem is that the method texture you are trying to find does not exist. If you look carefully at your declaration of the method signature in the GetMethodID call you will see "([Ljava/lang/String;)V" which is trying to find a method that accepts a String array as its parameter. Remove the [ from the method signature and it should work ok. You might want to test text (jmethodID) for NULL or 0 before trying to call it as well.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JNI - core dump - internal error on linux after calling Java method

    I'm getting a core dump after calling athe main statric method using JNNI.
    On linux.
    I can get the class id correcttly but when I attempt to call the method it craches with an internal error , anyone know why it would crash instead of just not work.
    if(cls)
        main_methodID = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
           printf("Class Found Successfully\n");
      else
        printf ( "cls not found\n");
        return 0;
      if(main_methodID)
              jstring first_str = env->NewStringUTF("The First String");//create string
              jobjectArray args = (jobjectArray)env->NewObjectArray(1,env->FindClass("java/lang/String"), first_str);//new array with 2 elements
                   env->SetObjectArrayElement(args, 2, first_str);//insert the second string into index 1 of the array
              jstring second_str = env->NewStringUTF("The Second String");//create string
              env->SetObjectArrayElement(args, 1, second_str);//insert the second string into index 1 of the array
         env->CallStaticVoidMethod(cls, main_methodID, args);//pass the array to the Java main method
                                  The JAVA method is
      public static void main(String[] args) {
        System.out.println("Main method in Framework");
            Framework framework = new Framework();
                                 

    I see yere points but what I see on linux is it makes it to the constructor of the Java object and somewhere afterwards it bails out, the Java app does work alone. It appears to have problems initializing the JFrame, could there be a problem with the Java inheritance when a JVM is invoked throurgh native invocation??
    Here's some of the Java stuff
    public class Framework extends WindowAdapter {
        public int numWindows = 0;
        private Point lastLocation = null;
        private int maxX = 500;
        private int maxY = 500;
        public Framework() {
            System.out.println("JAVA Framework cnst");//GETTING HERE
            makeNewWindow();
        public void makeNewWindow() {
            System.out.println("JAVA makeWindow"); //GETTING HERE
            JFrame frame = new MyFrame(this); //NOT GETTING HERE!!!!!!!!!
            numWindows++;
            System.out.println("Number of windows: " + numWindows);
            System.out.println("Frame location: " + lastLocation);
            frame.setVisible(true);
            System.out.println("Post Java set frame visible");
        public static void main(String[] args) {
        System.out.println("Main method in Framework");
            Framework framework = new Framework();//GETTING HERE
    class MyFrame extends JFrame {
        protected Dimension defaultSize = new Dimension(200, 200);
        protected Framework framework = null;
        public MyFrame(Framework controller) {
            super("New Frame");
            System.out.println("MyFrame cnst ");//NOT GETTING HERE!!!!!!
            framework = controller;
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            addWindowListener(framework);
            JMenu menu = new JMenu("Window");
            menu.setMnemonic(KeyEvent.VK_W);
           setSize(defaultSize);
    }

  • Runtime error Calling Java Methods from C++

    I'm trying to add Java methods to an existing C++ program.
    I'm working in W2000 enviroment using Cygnus GCC compiler.
    Before adding these methods, I tested invoke example from Jni tutorial.
    All worked properly. But the problems arouse when I tried to run non-static methods.
    Here is the code I'm testing now:
    #include <stdio.h>
    #include <jni.h>
    #define PATH_SEPARATOR ';'
    #define USER_CLASSPATH "." /* where Prog.class is */
    int main(int argc, char *argv[]) {
    JNIEnv *env;
    JavaVM *jvm;
    JDK1_1InitArgs vm_args;
    jint res;
    jclass cls;
    jmethodID mid;
    jobject jobj;
    char classpath[1024];
    vm_args.version = 0x00010001;
    JNI_GetDefaultJavaVMInitArgs(&vm_args);
    sprintf(classpath, "%s%c%s",
    vm_args.classpath, PATH_SEPARATOR, USER_CLASSPATH);
    vm_args.classpath = classpath;
    res = JNI_CreateJavaVM(&jvm,(void **)&env,&vm_args);
    if (res < 0) {
    fprintf(stderr, "Can't create Java VM\n");
    exit(1);
    cls = env->FindClass("Prog");
    if (cls == 0) {
    fprintf(stderr, "Can't find consola class\n");
    exit(1);
    mid = env->GetStaticMethodID(cls, "Entrada", "()V");
    if (mid == 0) {
    fprintf(stderr, "Can't find consola.consola\n");
    exit(1);
    env->CallStaticVoidMethod(cls, mid);
    /*     jobj = env->NewObject(cls, mid);
    if (jobj == 0) {
    fprintf(stderr, "Can't find Prog.main\n");
    exit(4);
    jvm->DestroyJavaVM();
    And the java code Prog.java:
    public class Prog {
    public static void Entrada() {
    Consola Cons = new Consola();
    And Consola a user class tha shows a Java window and let's do something more.
    These code works fine and The Prog and Consola classes run properly.
    But when I try to change Entrada method to non-static, following error appears in a window.
    Microsoft Visual C++ Runtime library
    Runtime Error !
    Program: D:\javaini\JNI-INVOKE\invoke.exe
    abnormal program termination
    If I try
    jobj = env->NewObject(cls, mid);
    if (jobj == 0) {
    fprintf(stderr, "Can't find Prog.main\n");
    exit(4);
    instead of
    env->CallVoidMethod(cls, mid);
    I get the same error.
    Could anybody help me ?
    Am I doing anything wrong ?
    Thanks in advance. Ignasi Villagrasa.

    I found it.
    In JNI examples I saw
    mid = env->GetMethodID(cls, "<init>", "()V");
    to run constructor.
    And then NewObject function.
    So it's solved.
    But I find another problem now.
    If the class I'm calling is a graphic java class (In this case from swing), when the window is closed the application in C++ stops too.
    Should I create another thread to manage the window ?
    Couldn't I follow running lines after NewObject method ?
    Thanks in advance, Ignasi Villagrasa.

  • How to call java method from C ?

    Hello,
    I try to call a native method from java which calls java method from the same class. Exception (noSuchMethodError) is thrown. Any ideas?
    Thanx in advance !
    here is the source of the native method :
    JNIEXPORT jint JNICALL Java_TestDll_Proc_1Mul_1Int_1Var_1Var_1Stdcall (JNIEnv * env, jclass jcl, jint jarg1, jint jarg2) {
    int arg1;
    int arg2;
    int arg3;
    jint res;
    char * ch = "test";
    jfieldID fid;
    jmethodID mid;
    int (* procedure) (int *, int * ,int *);
    int mch;
    arg1 = (int )jarg1;
    arg2 = (int )jarg2;
    procedure = GetProcAddress(libraryHandle,"Proc_Mul_Int_Var_Var_Stdcall");
    procedure(&arg1,&arg2,&arg3);
    res = (jint) arg3;
    printf("(*env)->GetMethodID(env, jcl, \"test\", \"()V\");\n");
    mid = (*env)->GetMethodID(env, jcl, "test", "()V");
    printf("(*env)->CallVoidMethod(env, jcl, mid);\n");
    (*env)->CallVoidMethod(env, jcl, mid);
    return res;
    here is the source of the java file:
    public class TestDll {
    static {
    System.loadLibrary("testdllwrap");
    System.out.println("java: Library testdllwrap.dll loaded");
    public TestDll() {
    public native int Proc_Mul_Int_Var_Var_Stdcall(int jarg1, int jarg2);
    public void test() {
    System.out.println("java: test()");
    public static void main(String[] args) {
    TestDll access = new TestDll();
    int a = 5;
    int b = 6;
    int c = 0;
    System.out.println("Calling Proc_Mul_Int_Var_Var_Stdcall");
    c = access.Proc_Mul_Int_Var_Var_Stdcall(a,b);
    System.out.println("Java Result = " + c);

    Something is wrong with the code you posted here.
    Since your native method is not static, it should have the jobject instance as a parameter in the function prototype, not a jclass. Also, you should be calling CallObjectMethod with a jobject, not jclass.
    Check out Jace at http://jace.reyelts.com/jace.
    To call the java method you would do:
    JNIEXPORT jint JNICALL Java_TestDll_Proc_1Mul_1Int_1Var_1Var_1Stdcall
    (JNIEnv * env, jobject jTestDll, jint jarg1, jint jarg2) {
      TestDll testDll( jTestDll );
      testDll.test();
    }God bless,
    -Toby Reyelts

  • Call Java Method from Callback function

    I am writing a JNI wrapper in c++ for a particular event driven DLL. The DLL makes a network connection to another device and then calls a callback function when events are raised on the device. The DLL has 3 basic functions: connect, disconnect, and registerEventListener. RegisterEventListener takes a function pointer which is called each time an event is raised on the device.
    My wrapper DLL exposes connect and disconnect functions via JNI. I can call these functions just fine from my Java code. Now the question... How do I call a Java method from my c++ callback function? I can call a Java method using env->CallXXXMethod(...) from within a function that is accessible to Java but I don't have access to the JNI parameters in my Callback function.
    So how do I call a Java method from a callback function? If this cannot be done then what is the "right way" to handle native event notification with JNI?

    jschell wrote:
    JNI parameters? Meaning what exactly?
    General outline of a callback
    1. Entry
    2. Get the VM, env - there are methods for this
    3. Attach the thread
    4. Get a java object - how depends on what you are doing, but create it or a static reference.
    5. Get the java method
    6. Call the java method.That is exactly correct. The callback function is called from a separate thread so using a cached pointer to JNIEnv, obtained from the original native method, crashes the JVM. The jmethodID and jclass objects (which are needed to call the static Java method) can be cached without problem. The following is the code I used to attach the current thread and call my static method.
    void MyClass::onEvent(int system_id, char* data)
         //get a pointer to the Java Environment
         JNIEnv *env;
         jvm->AttachCurrentThread((void **)&env, NULL);
         //Call the Java method with the newly aquired data
         jstring js = env->NewStringUTF(data);
         env->CallStaticVoidMethod(cls, mid, system_id, js);
    }My last question is about cleanup in this function. When I use NewStringUTF to "convert" my char* to jstring do I need to do anything special to clean up or will the Java garbage collector take care of it since the jstring is being passed to a Java method?
    Thanks for you help

  • Any way (event) to call Java method after view created in JSF 2.0

    Hi,
    I am using JSF 2.0 Mojarra's implementation.
    I am interested to know if there is a way to call Java methods before and/or after view has been restored.
    I wanted to initialize data for my page in this Java method.
    I could see there is an event class PostRestoreStateEvent added in JSF 2.0. How to use it?
    I tired to use f:event element as below, but it does not work. Can anyone share anyother idea to achieve this behaviour?
    <f:metadata>
    <f:event type="postRestoreState" listener="#{employeeLoadBean.loadAfterRestoreView}"/>
    </f:metadata>
    Regards,
    Kishore K S

    Hi,
    The problem is solved as below.
    <f:metadata>
    <f:event type="javax.faces.event.PostRestoreStateEvent" listener="#{employeeViewEventListener.postRestoreState}"/>
    </f:metadata>
    The above calls the Java method #{employeeViewEventListener.postRestoreState} whenever View has been restored.
    It was not working when shortName of the event (ie., postRestoreState) is given and throwing ClassNotFound exception.
    Regards,
    Kishore K S

  • How to call a C function calling a Java Method from another C function ?

    Hi everyone,
    I'm just starting to learn JNI and my problem is that I don't know if it is possible to call a C function calling a Java Method (or doing anything else with JNI) from another C function.
    In fact, after receiving datas in a socket made by a C function, I would like to create a class instance (and I don't know how to do it too ; ) ) and init this instance with the strings I received in the socket.
    Is all that possible ?
    Thank you very much for your help !

    Hard to understand the question, but by most interpretations the answer is going to be yes.
    You do of course understand that JNI is the "API" that sits between Java and C and that every call between the two must go through that. You can't call it directly.

Maybe you are looking for

  • Photoshop CS4 Crashing Consistantly

    Seems CS4 just can't handle me having more than just a few high resolution files open at the same time before it crashes. My photos are fairly "process heavy" with multiple layers and text etc., but still not overly huge files that this should behapp

  • New Problem...installing Ovi maps

    cant install even update in facebook,internet radio... i got the latest nokia suite... Solved! Go to Solution.

  • Lightroom/ACR colours for Leica M8

    I am (and have been for a number of months) trying unsuccessfully to obtain good colour with both LR1.3.1 and ACR4.3.1 with DNG files from a Leica M8. I have expended many hours running calibration routines (Thomas Fors and Rags Gardner's scripts) to

  • Transfering my mail to new Macbook?

    I am ugrading to a Macbook from an iBook and I wanted to know if there is a file somewhere that contains all of my mail on my iBook (tiger) that I could copy to my new Macbook. Would be nice to still have access to my old email. Thanks F

  • Where is Arrangement button for folder columns?

    Where is Arrangement button for folder columns?  It does not show on top with the other buttons like Date modified, Date last opened, etc