android - 无法在 Android 的单个 native C++ 库文件中使用多个函数

标签 android c++ java-native-interface

我正在开发一个使用 C++ native 库的 Android 应用程序。我已经将 C++ 集成到我的项目中,并成功地通过 JNI 从 Java 调用 C++ 函数。但问题是我无法在单个 C++ native 库中声明多个函数。

这是我在 native-lib.cpp 文件中的原生 C++ 代码

#include <jni.h>
#include <string>

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <iostream>
#include <fstream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/stitching.hpp>
#include <vector>

using namespace std;
using namespace cv;

extern "C" {
JNIEXPORT
jstring
Java_media_memento_memento_SphereCameraActivity_stitchPhotos(
        JNIEnv *env,
        jobject ) {

    std::string hello = "This is the function one";
    return env->NewStringUTF(hello.c_str());
}



}

在 Java 中,我像这样加载库

static {
      System.loadLibrary("native-lib");
   }

并调用函数。它正在工作。但我确实将新函数添加到 native-lib.cpp,如下所示。

#include <jni.h>
#include <string>

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <iostream>
#include <fstream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/stitching.hpp>
#include <vector>

using namespace std;
using namespace cv;

extern "C" {
JNIEXPORT
jstring
Java_media_memento_memento_SphereCameraActivity_stitchPhotos(
        JNIEnv *env,
        jobject ) {

    std::string hello = "This is the function one";
    return env->NewStringUTF(hello.c_str());
}

    JNIEXPORT
jstring
Java_media_memento_memento_SphereCameraActivity_sayHello(
        JNIEnv *env,
        jobject ) {
    std::string hello = "Stitching the photo in C++";
    return env->NewStringUTF(hello.c_str());
}

}

如您所见,新函数是 sayHello。当我运行我的应用程序并从 java 调用 sayHello 函数时,应用程序崩溃了。

logcat 中的错误似乎与问题根本无关。

enter image description here

如何解决问题并在单个原生 C++ 库文件中使用多个函数?

最佳答案

我试过这样做并且它正在工作:

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring

JNICALL
Java_com_package_name_Keys_apiKey(JNIEnv *env, jobject object)
{
    std::string api_key = "https://api.api.net";
    return env->NewStringUTF(api_key.c_str());
}

extern "C" JNIEXPORT jstring

JNICALL
Java_com_package_name_Keys_imageApiKey(JNIEnv *env, jobject object)
{
    std::string image_api_key = "https://api.api.com/";
    return env->NewStringUTF(image_api_key.c_str());
}

关于android - 无法在 Android 的单个 native C++ 库文件中使用多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49901602/

相关文章:

java - java.net 包如何工作?

java - android getRelativeTimeSpanString 月份始终是一月

java - 通过接口(interface)在Realm对象中添加方法

Android:安排剩余事件

c++ - 骑士之旅将数组传递到链表等等

c++ - 对音频信号进行编码是否有任何限制?

c++ - 为什么我可以将 Int 分配给 String 而不会出现编译器错误?

java - 使用 Eclipse 开发 JNI 应用程序(结合 Java/C++)

android - 我们可以用任何其他方式在 Android 中访问 C++ 代码而不是使用 JNI

java - Java 中的 GUI,SML 中的后端?