I have a short question related to the GetMethodID() function of C . I have been searching for the answer here on StackOverflow, but could not find it. My main code is in Java, but for some parts I would need C . The code below is a simplification of what I intend to implement, to test out how to retrieve and pass objects between Java and C . The final issue is presented at the end of this pos. First, I present the implementation.
public class ExampleJNI {
static {
System.loadLibrary("nativeObject");
}
public static void main(String[] args){
ExampleJNI tmp = new ExampleJNI();
Order o = tmp.createOrder(1,2,3,4);
if (o != null){
System.out.println(o.toString());
} else {
System.out.println("Errors present");
}
}
// Try passing a list
public native Order createOrder(int a, int b, int c, int d);
}
The order class is defined to be:
public class Order {
// Order attributes
public final int a;
public final int b;
public final int c;
public final int d;
private int e;
public Order(int a, int b, int c, int d){
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
@Override
public String toString(){
return a "," b "," c "," d;
}
}
I have the following implementation in C .
#include "ExampleJNI.h"
#include <iostream>
#include <vector>
/*
* Class: ExampleJNI
* Method: createOrder
* Signature: (IIII)LOrder;
*/
JNIEXPORT jobject JNICALL Java_ExampleJNI_createOrder(JNIEnv* env, jobject thisObject, jint a, jint b, jint c, jint d){
// Get a class reference for Order
jclass cls = env->GetObjectClass(thisObject);
if (cls == NULL){
std::cout << "Class not found" << std::endl;
return NULL;
}
// Get the method ID of the constructor whick takes four integers as input
jmethodID cid = env->GetMethodID(cls, "<init>", "(IIII)V");
if (cid == NULL){
std::cout << "Method not found" << std::endl;
return NULL;
}
return env->NewObject(cls, cid, a, b, c, d);
}
When I run the code, "Method not found" is printed, which indicates that something is going wrong when calling the GetMethodID. I also retrieve the following exception error:
Exception in thread "main" java.lang.NoSuchMethodError: <init>
at ExampleJNI.createOrder(Native Method)
at ExampleJNI.main(ExampleJNI.java:11)
Any suggestions on what I should have instead of the <init>
are highly appreciated!
CodePudding user response:
thisObject
is a ExampleJNI
not a Order
so GetObjectClass
will return ExampleJNI
which doesn't have the constructor you are looking for. Change GetObjectClass
to env->FindClass("Order")
.