我有一個與 C 的 GetMethodID() 函式相關的簡短問題。我一直在 StackOverflow 上尋找答案,但找不到。我的主要代碼是用 Java 撰寫的,但對于某些部分,我需要 C 。下面的代碼是我打算實作的簡化,以測驗如何在 Java 和 C 之間檢索和傳遞物件。最后一個問題在這篇文章的末尾提出。首先,我介紹實作。
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);
}
訂單類定義為:
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;
}
}
我在 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);
}
當我運行代碼時,會列印“Method not found”,這表明呼叫 GetMethodID 時出現了問題。我還檢索到以下例外錯誤:
Exception in thread "main" java.lang.NoSuchMethodError: <init>
at ExampleJNI.createOrder(Native Method)
at ExampleJNI.main(ExampleJNI.java:11)
任何關于我應該有什么而不??是什么的建議<init>都非常感謝!
uj5u.com熱心網友回復:
thisObjectis a ExampleJNInot a Orderso GetObjectClasswill returnExampleJNI它沒有您要查找的建構式。更改GetObjectClass為env->FindClass("Order")。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/436696.html
