5

I'm writing a simple program to call a Java function from my C program.

Following is my code:

#include <jni.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>

JNIEnv* create_vm() {
    JavaVM* jvm;
    JNIEnv *env;
    JavaVMInitArgs vm_args;

    JavaVMOption options[1];

    options[0].optionString - "-Djava.class.path=/home/chanders/workspace/Samples/src/ThreadPriorityTest";
    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 1;
    vm_args.options = &options;
    vm_args.ignoreUnrecognized = JNI_FALSE;

    JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    return env;
}

void invoke_class(JNIEnv* env) {
    jclass helloWorldClass;
    jmethodID mainMethod;
    jobjectArray applicationArgs;
    jstring applicationArg0;

    helloWorldClass = (*env)->FindClass(env, "InvocationHelloWorld");
    mainMethod = (*env)->GetStaticMethodID(env, helloWorldClass, "main", "([Ljava/lang/String;)V");

    applicationArgs = (*env)->NewObjectArray(env, 1, (*env)->FindClass(env, "java/lang/String"), NULL);
    applicationArg0 = (*env)->NewStringUTF(env, "From-C-program");
    (*env)->SetObjectArrayElement(env, applicationArgs, 0, applicationArg0);
    (*env)->CallStaticVoidMethod(env, helloWorldClass, mainMethod, applicationArgs);
}

int main() {
    JNIEnv* env = create_vm();
    invoke_class(env);
}

I'm compiling the above program using: gcc -o invoke -I$JAVA_HOME/include/ -I$JAVA_HOME/include/linux -L$JAVA_HOME/jre/lib/amd64/server/ ThreadPriorityTest.c

and i'm getting the following error:

/tmp/ccllsK5O.o: In function `create_vm': ThreadPriorityTest.c:(.text+0x35): undefined reference to `JNI_CreateJavaVM' collect2: ld returned 1 exit status

I'm not really sure what is causing this problem

UPDATE 1

Included the -ljvm in the command line and then got a undefined reference to FUNCTION_NAME I'm running it on Rhel 6.2

3

1 Answer 1

5

You've got the path to the Java library (the -L option), but not the library itself. You need to include -ljvm on the link line as well.

Sign up to request clarification or add additional context in comments.

4 Comments

I tried it, but am not getting a bunch of undefined reference. I have updated my question.
Do you mean literally FUNCTION_NAME (I have no clue if so) or do you mean generically a lot of other undefined functions?
i mean lot of other undefined functions
Give us a list of some of them, and we'll tell you what other libraries to include.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.