gpt4 book ai didi

java - 尽管在主要 Activity 中工作,但 native 函数在自定义 View 中抛出 UnsatisfiedLinkError

转载 作者:行者123 更新时间:2023-11-28 01:09:01 25 4
gpt4 key购买 nike

出于某种原因,我只能从我的主要 Activity 中调用 native 函数,而不能调用我创建的任何自定义 View 。这是一个示例文件(我遵循了教程,但将类重命名为 http://mindtherobot.com/blog/452/android-beginners-ndk-setup-step-by-step/ )

查看 native 函数“getNewString”的用法。

package com.example.native;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;

public class NativeTestActivity extends Activity
{
static
{
System.loadLibrary("nativeTest");
}

private native String getNewString();

@Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(new BitmapView(this));

String hello = getNewString(); // This line works fine
new AlertDialog.Builder(this).setMessage(hello).show();
}
}

class BitmapView extends View
{
static
{
System.loadLibrary("nativeTest");
}

private native String getNewString();

public BitmapView(Context context)
{
super(context);

String hello = getNewString(); // This line throws the UnsatisfiedLinkError
new AlertDialog.Builder(this.getContext()).setMessage(hello).show();
}
}

如何在自定义 View 中调用原生函数?

我已将该应用程序构建为 Android 2.2 应用程序。我正在我的 HTC Desire 上运行该应用程序。我有最新的 SDK (9) 和最新的 NDK (r5)。

最佳答案

您的问题是您正试图从它不属于的类中调用 native 函数。

您在 c 文件中定义了以下 JNI 函数:

jstring Java_com_example_native_NativeTestActivity_getNewString()

这说明加载时的 native 函数将与 NativeTestActivity 类中声明为 native 的方法绑定(bind)。因此,当您尝试从您的 View 类调用它时,它找不到任何要绑定(bind)的函数。

在这种情况下,它将查找以下函数(当然,您的 .so 中不存在该函数):

jstring Java_com_example_native_BitmapView_getNewString()

如果您仍然希望能够从不同的类调用相同的函数,您可以在容器类中声明它,该容器类可以从您想要的任何类访问。

例如:

java代码:

package com.example.native;
public class NativeHelper {
public native String getNewString();
static
{
System.loadLibrary("nativeTest");
}
}

c代码:

jstring Java_com_example_native_NativeHelper_getNewString(JNIEnv* env, jobject javaThis)
{
return (*env)->NewStringUTF(env, "Hello from native code!");
}

关于java - 尽管在主要 Activity 中工作,但 native 函数在自定义 View 中抛出 UnsatisfiedLinkError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4499071/

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