Grumblesaurus
Grumblesaurus

Reputation: 3119

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

I am writing a native launcher in linux for a java program. The launcher should load libjvm.so statically and execute the function JNI_CreateJavaVM() via a function pointer, so I can launch the executable without having to first set LD_LIBRARY_PATH.

I have this so far and I've figured it how to compile and link it, but I'm struggling with the syntax for declaring the function pointer and then later executing the function:

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. 

What magic words do I put in place of the ??s to make this work? I've tried working through the dlsym documentation, but I'm too unfamiliar with C/C++ to translate it to my situation.

Thanks!

Upvotes: 0

Views: 188

Answers (1)

Botje
Botje

Reputation: 30807

First, declare a type (here p_JNI_CreateJavaVM) for the function you want to retrieve:

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

And you can invoke it as usual:

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

Upvotes: 2

Related Questions