在.so库中更改函数名称 [英] Change function name in a .so library
问题描述
我只有1个来自旧项目的.so文件. 如何在不在项目或模块中创建相同的程序包的情况下使用此文件?
I only have 1 .so file from old project. How can I use this file without creating the same package in project or module ?
推荐答案
实际上,您不需要更改.so
文件中的函数名称.您可以使用 dlopen
在运行时动态加载.so
库,而 dlsym
为您获取指针YOUR_FUNCTION_NAME()
,然后通过指针调用YOUR_FUNCTION_NAME()
.为此,您可以像这样创建包装器":
Actually, you don't need to change function name in .so
file. You can use dlopen
to load your .so
library dynamically at runtime and dlsym
to get pointer for you YOUR_FUNCTION_NAME()
and then call YOUR_FUNCTION_NAME()
by pointer. For do that in your current project you can create "wrapper" like that:
public class OldSoHelper {
public static native void loadOldSo();
public static native <TYPE_OF_RESULT> runFunFromOldSo(<PARAMETERS>);
public static native void unloadOldSo();
}
以及当前项目的相应.c/.cpp
文件中的文件(例如,默认情况下为native-lib.cpp
):
and in corresponding .c/.cpp
file of current project (e.g. native-lib.cpp
by default):
void *handle;
<TYPE_OF_OLD_FUNCTION> (*old_fun_wrapper)(<PARAMETERS_OF_OLD_FUNCTION>);
extern "C"
JNIEXPORT void JNICALL
Java_<YOUR_PACKAGE_NAME>_OldSoHelper_loadOldSo(JNIEnv *env, jclass type) {
handle = dlopen("<YOUR_OLD_SO>.so", RTLD_NOW);
old_fun_wrapper = (<TYPE_OF_OLD_FUNCTION> (*)(<PARAMETERS_OF_OLD_FUNCTION>))(dlsym(handle, "<OLD_FUNCTION_NAME_e.g._Java_com_abc_dee_Native_appInit>"));
}
extern "C"
JNIEXPORT jobject JNICALL
Java_<YOUR_PACKAGE_NAME>_OldSoHelper_runFunFromOldSo(JNIEnv *env, jclass type,
<PARAMETERS_FOR_OLD_FUNCTION>)
{
jclass ResultClass = env->FindClass("YOUR/PACKAGE/NAME/RESULT_CLASS");
jobject result = ...
jfieldID fieldId = env->GetFieldID(ResultClass, "<FIELD_NAME>", "<FILED_TYPE_LETTER>");
<TYPE_OF_OLD_FUNCTION> res = old_fun_wrapper(<PARAMETERS_FOR_OLD_FUNCTION>);
env->Set<TYPE>Field(result, fieldId , res.filed);
return result;
}
extern "C"
JNIEXPORT void JNICALL
Java_<YOUR_PACKAGE_NAME>_OldSoHelper_unloadOldSo(JNIEnv *env, jclass type) {
if (handle) {
dlclose(handle);
}
}
,您可以从Java代码中调用:
and from java code you can call:
...
// when you need old .so e.g. in onCreate()
OldSoHelper.loadOldSo();
...
// when you no need to call function from old .so
<TYPE_OF_RESULT> result = OldSoHelper.runFunFromOldSo(<PARAMETERS>);
...
// when you no need old .so e.g. in onDestroy()
OldSoHelper.unloadOldSo();
...
这篇关于在.so库中更改函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!