![](/img/trans.png)
[英]Android JNI java.lang.NoSuchMethodError: no non-static method
[英]Using non-static objects in jni in java
我正在尝试学习jni,我想知道如何实现它,以便java对象在jni c ++层中可以具有与其相关的一些值。 目前,我有此Java代码。
public class Test
{
static
{
Runtime.getRuntime().loadLibrary("JNITests");
}
public native void setValue(int value);
public native int getValue();
public static void main(String[] args)
{
Test test1 = new Test();
test1.setValue(34);
Test test2 = new Test();
test2.setValue(23);
System.out.println(test1.getValue());
}
}
所以我想做的就是使用此c ++代码使每个Test对象使用setValue和getgetValue在jni中存储一个值。
#include <jni.h>
#include "Test.h"
int value;
JNIEXPORT void JNICALL Java_Test_setValue(JNIEnv *, jobject, jint newValue)
{
value = newValue;
}
JNIEXPORT jint JNICALL Java_Test_getValue(JNIEnv *, jobject)
{
return value;
}
但是,问题是,当我在test2上使用setValue时,然后我打印test1的值时,它已更改为我将test2设置为的值。 我该如何解决。 我尝试将每个jobject映射到一个int值,但这也不起作用。
可能的解决方案可能是在本机代码中使用动态分配的结构。 为此,您必须分配(例如,在构造函数中)一些保存该结构的内存。 该结构的地址被传递回Java部件并存储在Java对象中。 然后,对于getValue
和setValue
,将添加一个参数,该参数保存分配的结构的内存地址,然后可用于存储该值。 销毁对象时,必须手动释放内存。
使用您的代码,本机部分可能看起来像:
#include <cstdlib>
#include <jni.h>
#include "Test.h"
struct data {
int value;
};
JNIEXPORT void JNICALL Java_Test_setValue0(JNIEnv *, jobject, jlong address, jint newValue)
{
struct data *ptr = (struct data *)address;
ptr->value = newValue;
}
JNIEXPORT jint JNICALL Java_Test_getValue0(JNIEnv *, jobject, jlong address)
{
struct data *ptr = (struct data *)address;
return ptr->value;
}
JNIEXPORT jlong JNICALL Java_Test_construct0(JNIEnv *, jobject) {
struct data *ptr = (struct data *)malloc(sizeof(*ptr));
return (jlong)ptr;
}
JNIEXPORT void JNICALL Java_Test_destruct0(JNIEnv *, jobject, jlong address) {
struct data *ptr = (struct data *)address;
free(ptr);
}
然后,Java部分将如下所示:
public class Test
{
static
{
Runtime.getRuntime().loadLibrary("JNITests");
}
private long address;
private native long construct0();
private native void destruct0(long address);
private native void setValue0(long address, int value);
private native int getValue0(long address);
public Test() {
this.address = this.construct0();
}
@Override
public void finalize() {
this.destruct0(this.address);
super.finalize();
}
public void setValue(int value) {
this.setValue0(this.address, value);
}
public int getValue() {
return this.getValue0(this.address);
}
public static void main(String[] args)
{
Test test1 = new Test();
test1.setValue(34);
Test test2 = new Test();
test2.setValue(23);
System.out.println(test1.getValue());
}
}
我重命名了本机方法,以在不更改API的情况下引入address
参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.