Change function name in a .so library

 ̄綄美尐妖づ 提交于 2020-02-05 04:33:04

问题


I only have 1 .so file from old project. How can I use this file without creating the same package in project or module ?


回答1:


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();
}

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);
     }
}

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();
...


来源:https://stackoverflow.com/questions/54782251/change-function-name-in-a-so-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!