如何从 linux 中的静态加载库执行函数?

How to execute a function from a statically loaded library in linux?

我正在 linux 中为 java 程序编写本机启动器。启动程序应该静态加载 libjvm.so 并通过函数指针执行函数 JNI_CreateJavaVM(),这样我就可以启动可执行文件而无需先设置 LD_LIBRARY_PATH

到目前为止我已经有了这个,我已经想出了如何编译和 link 它,但是我正在为声明函数指针然后执行函数的语法而苦苦挣扎:

JavaVM *jvm;
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption* options = new JavaVMOption[10];

...

std::string location = "./jre/lib/server/libjvm.so";
void *handle = dlopen ( location.c_str(), RTLD_LAZY );

if ( !handle ) {
   printf ( "Unable to load %s, exiting", location.c_str() );
   return 0;
}

?? = dlsym ( handle, "JNI_CreateJavaVM" ); //get the function pointer

//This is how I would execute the function if dynamically linking: 
//JNI_CreateJavaVM( &jvm, (void**)&env, &vm_args );

?? ( &jvm, (void**)&env, &vm_args ); //Execute the function pointer. 

我用什么神奇的词来代替 ?? 来完成这项工作?我尝试过 dlsym documentation,但我对 C/C++ 太陌生,无法将其转化为我的情况。

谢谢!

首先,为您要检索的函数声明一个类型(此处p_JNI_CreateJavaVM):

typedef jint (*p_JNI_CreateJavaVM)(JavaVM**, void**, void**);
p_JNI_CreateJavaVM JNI_CreateJavaVM = (p_JNI_CreateJavaVM)dlsym(handle, "JNI_CreateJavaVM");

您可以照常调用它:

jint ret = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);