我正在开发一个使用 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 中的错误似乎与问题根本无关。
如何解决问题并在单个原生 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/