我是 stackoverflow 的新手,我想寻求有关 Android C++ 的帮助。
这是我的主要 JNI 实现(native-lib.cpp
):
#include <jni.h>
#include <string>
#include <dlfcn.h>
#include "external.hpp"
extern "C" JNIEXPORT jstring JNICALL
Java_com_useless_myapplication_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
void* handle;
void (*funcext)();
handle = dlopen("libexternal.so",RTLD_LAZY);
funcext = (void (*)(void))dlsym(handle, "_Z5func2v");
try {
funcext();
}
catch (MyException &err)
{
std::string hello = "MyException from C++";
return env->NewStringUTF(hello.c_str());
}
catch (GenericException &err)
{
std::string hello = "GenericException from C++";
return env->NewStringUTF(hello.c_str());
}
catch (GenericException* err)
{
std::string hello = "GenericException* from C++";
return env->NewStringUTF(hello.c_str());
}
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
这是我的libexternal.so
实现(external.cpp
):
#include <jni.h>
#include <string.h>
#include "external.hpp"
GenericException::GenericException(){};
GenericException::GenericException(int errcode,char* msg)
{
errorcode = errcode;
memset(message,0,256);
strcpy(message,msg);
}
MyException::MyException(int errcode,char* msg)
{
errorcode = errcode;
memset(message,0,256);
strcpy(message,msg);
}
void func()
{
throw MyException(10,"Error1!");
}
bool func3()
{
try {
func();
}
catch (GenericException &err)
{
return false;
}
return true;
}
void func2()
{
if (!func3())
throw MyException(11,"Error2!");
}
external.hpp
文件定义如下:
void func();
void func2();
bool func3();
class GenericException
{
public:
GenericException();
GenericException(int errcode,char* msg);
protected:
int errorcode;
char message[256];
};
class MyException : public GenericException
{
public:
MyException(int errcode,char* msg);
};
程序编译和链接干净但是当我运行它时我的 android 应用程序崩溃并在 logcat 中显示以下消息:
2018-11-14 09:57:42.058 6519-6519/com.useless.myapplication A/libc: /usr/local/google/buildbot/src/android/ndk-release-r18/external/libcxx/../../external/libcxxabi/src/abort_message.cpp:73: abort_message: assertion "terminating with uncaught exception of type MyException" failed
当我尝试执行 external.cpp
第 41 行时出现错误:
throw MyException(11,"Error2!");
正如我发现的其他帖子所建议的那样,我尝试在我的应用 build.gradle
cppflgs 中启用 -frtti
标志,但这并没有解决错误。
我尝试在 Linux 和 MacOS 上运行相同的代码(老实说没有 Java 顶层),但在这些平台上,异常被 native-lib.cpp
代码。
关于 Android 中的 C++ 异常,有什么我不知道的吗? 我怎样才能捕捉到我在 Android 上使用 dlopen 加载的库抛出的异常?
谢谢
最佳答案
你的异常类型没有关键函数,所以它的类型信息是用 vague linkage 发出的.这意味着它在每个使用它的库中都是弱符号。
您的 JNI 库加载并解析它自己的类型信息。然后加载您的 dlopened 库并解析其自己的类型信息,因为它无法访问父作用域(System.loadLibrary
使用 RTLD_LOCAL
)。因此,您的异常类型有两个单独的类型信息对象。通过比较 typeinfo 对象的地址来检查 RTTI 相等性(参见 C++ ABI spec )。
我不确定如果不直接将您的 JNI 代码链接到 libexternal.so 是否可以解决这个问题。如果您添加实现此功能所需的关键函数(将在 libexternal.so 中定义),那么我相信您需要链接到它以便您的 JNI 代码链接。
关于安卓 C++ : uncaught exception from loaded shared library,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53297295/