dcsimg
Accessing Java classes from C++
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   David_Burgos
Posted On:   Thursday, April 25, 2002 05:01 AM

Hi all. I am programming a JNI interface and I need to access Java from the native side. If I try with a "plain" class there is no problem at all: public class Clase1 { private int A; public void setA(int a) { A = n; } public int getA() { return A; } } Let miObjeto an instance of ClaseA, if I call this C++ function from Java everything works correctly: JNIEXPORT void JNICALL Java_Ejemplo_escribeA(JNIEnv *env, jobject miObjeto) { jclass miClase = env->GetObjectClass(miObjeto); jmethodID   More>>

Hi all.


I am programming a JNI interface and I need to access Java from the native side. If I try with a "plain" class there is no problem at all:


public class Clase1
{
private int A;

public void setA(int a)

{

A = n;

}

public int getA()

{

return A;

}

}



Let miObjeto an instance of ClaseA, if I call this C++ function from Java everything works correctly:




JNIEXPORT void JNICALL Java_Ejemplo_escribeA(JNIEnv
*env, jobject miObjeto)



{
jclass miClase = env->GetObjectClass(miObjeto);

jmethodID miMetodo = env->GetMethodID(miClase,
"setA", "(I)V");

if (miMetodo == 0) return;

env->CallVoidMethod(miObjeto, mSetCurrTransponder,
123);

}



Fine. I read "123" from the Java side after calling the Ejemplo_escribeA JNI method. But now I need to use some Java classes like this:



public class Clase2
{
public Clase1 B;

private int C;

...

}



So if I want to access the setA method, I need to get an instance of B first. I am doing the following:



JNIEXPORT void JNICALL
Java_Ejemplo_escribeObjeto2(JNIEnv *env, jobject
miObjeto)


{
jclass miClase = env->GetObjectClass(miObjeto);

jfieldID miCampo = env->GetFieldID(miClase, "B",
"LClase1;");

if (miCampo == 0) return;

jobject miObjeto2 =
(jobject)env->GetObjectField(miClase, miCampo);

if (miObjeto2 == 0) return;




// Alright, no problem, the B field is found cause the
// function does not return. Now, I try to repeat the same
// with the B object:



jclass miClase2 = env->GetObjectClass(miObjeto2);

if (miClase2 == 0) return;

jmethodID miMetodo = env->GetMethodID(miClase2,
"setA", "(I)V");

if (miMetodo == 0) return;




// And the function exits here because the setA method


// can't be found.

...

}



Any idea?



Thanks in advance.



David.

   <<Less

Re: Accessing Java classes from C++

Posted By:   Anthony_Pham  
Posted On:   Thursday, May 9, 2002 04:25 PM

You have to first create an instance of the java class first by calling its construction. After sucessfully, you now can start to call its instance's method.
About | Sitemap | Contact