我正在编写一个简单的程序来从我的C程序中调用Java函数。使用jni从c调用java函数
以下是我的代码:
#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);
}
我编译使用上述程序: 的gcc -o调用-I $ JAVA_HOME /包括/ -I $ JAVA_HOME /在include/linux -L $ JAVA_HOME/JRE/lib目录/ AMD64 /服务器/ ThreadPriorityTest.c
,我发现了以下错误:
/tmp/ccllsK5O.o: In function `create_vm': ThreadPriorityTest.c:(.text+0x35): undefined reference to `JNI_CreateJavaVM' collect2: ld returned 1 exit status
我真的不知道是什么原因造成这个问题
更新1
包括在命令行中-ljvm,然后得到了一个undefined reference to FUNCTION_NAME
我运行它在RHEL 6.2
看看http://stackoverflow.com/questions/7680415/calling-java-code-from-c-in-an-android-application – aProgrammer 2012-03-30 05:11:08
尝试过,但它开始给我一堆未定义的引用。 – 2012-03-30 05:12:32
或http://www.codeproject.com/Questions/263687/Linker-error-undefined-reference-to-_imp__JNI_Crea – aProgrammer 2012-03-30 05:13:00