您可以在另一个应用程序中使用一个应用程序中的.so库吗?

问题描述 投票:0回答:2

[如果有一个具有.so lib的应用程序。说“ example.so”,其功能类似于Java_com_domain_demo_exampleFuntion,可以从具有不同应用程序ID的应用程序中调用它吗?

如果新的应用程序ID为com.otherdomain.demo2,则出现类似错误

找不到无效的Java_com_otherdomain_demo2_exampleFuntion()的实现

android c++ java-native-interface lib
2个回答
0
投票

您可以用来创建特殊的模块(相同的软件包名称),其名称类似于Java_com_domain_demo_exampleFuntion()。然后您使用另一个应用程序使用此模块。但是,您不能将* .so文件用于其他具有不同程序包名称的应用程序。


0
投票

如果无法重命名应用程序,还有另一种方法:编写一个小的.so文件,该文件与example.so链接,并在其registerNatives函数中调用JNI的JNI_OnLoad

以下示例改编自Android JNI documentation

JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
    JNIEnv* env;
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
        return JNI_ERR;
    }

    // Find your class. JNI_OnLoad is called from the correct class loader context for this to work.
    jclass c = env->FindClass("com/markov/App/MyClass");
    if (c == nullptr) return JNI_ERR;

    // Register your class' native methods.
    static const JNINativeMethod methods[] = {
        {"myExampleFunction", "()V", reinterpret_cast(Java_com_domain_demo_exampleFuntion)},
    };
    int rc = env->RegisterNatives(c, methods, sizeof(methods)/sizeof(JNINativeMethod));
    if (rc != JNI_OK) return rc;

    return JNI_VERSION_1_6;
}

此示例将Java_com_domain_demo_exampleFuntion绑定到com.markov.App.MyClass#myExampleFunction。当然,您可以向methods数组添加更多功能。

请注意,您复制的函数的行为可能取决于您将其绑定到的类的某些字段。如果com.markov.App.MyClass类上不存在这些字段,则JNI调用将失败或崩溃。例如,许多Java包装器都使用long字段来存储指向C内存的指针。

© www.soinside.com 2019 - 2024. All rights reserved.