gpt4 book ai didi

java - 从 JNI 调用 Java Enum 方法

转载 作者:行者123 更新时间:2023-12-02 10:58:26 25 4
gpt4 key购买 nike

我有一个场景,我需要在 native 代码中调用枚举方法。该枚举是在 Java 中定义的。

public enum Pool {
JNIPOOL(new SomePoolStrategyImp()),
UIPOOL(new RandomPoolStrategyImp());

private PoolStrategy poolStrategy;

Pool(PoolStrategy poolStrategy) {
this.poolStrategy = poolStrategy;
}

public Bitmap getBitmap(int width, int height) {
// some logic
// return poolStrategy.getBitmap(width, height);
}
}

我有可以从 JNI 调用对象方法的引用,但就我而言,我需要调用已经创建的对象方法。就像我需要从 native 代码调用 JNIPOOL.getBitmap() 一样。谁能帮我这个?我只想了解可以帮助我的方法或任何现有博客。

谢谢!

最佳答案

正如我已经说过的,枚举常量只是一个字段。

为了测试我的解决方案,我使用了具有以下签名的 native 方法:

private static native Bitmap callBitmap(int width, int height);

在类test.JNITest中。这是 C++ 中的 native 代码:

JNIEXPORT jobject JNICALL Java_test_JNITest_callBitmap
(JNIEnv * env, jclass clazz, jint width, jint height) {
// Get a reference to the class
jclass poolc = env->FindClass("test/Pool");
// get the field JNIPOOL
jfieldID jnipoolFID = env->GetStaticFieldID(poolc, "JNIPOOL", "Ltest/Pool;");
jobject jnipool = env->GetStaticObjectField(poolc, jnipoolFID);

// Find the method "getBitmap", taking 2 ints, returning test.Bitmap
jmethodID getBitmapMID = env->GetMethodID(poolc, "getBitmap", "(II)Ltest/Bitmap;");

// Call the method.
jobject result = env->CallObjectMethod(jnipool, getBitmapMID, width, height);

return result;
}

关于java - 从 JNI 调用 Java Enum 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51537502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com