我正在尝试使用JNI在我的C++程序中加载以下Java类:
package helloWorld;
import org.apache.log4j.Logger;
public class HelloWorld{
private static final Logger logger = Logger.getLogger(HelloWorld.class);
public static void main(String[] args){
System.out.println("Hello, World");
}
public static int square(int input){
int output = input * input;
return output;
}
public static int power(int input, int exponent){
int output,i;
output=1;
for(i=0;i<exponent;i++){
output *= input;
}
return output;
}
}
它依赖于log4j-1.2.16.jar。
这是我的C++代码:
#include <stdio.h>
#include <cstdlib>
#include "../Header/jni.h"
JNIEnv* create_vm(JavaVM **jvm)
{
char * classPath = (char *) "-Djava.class.path=HelloWorld-0.0.1-SNAPSHOT.jar";
JNIEnv* env;
JavaVMInitArgs args;
JavaVMOption options[2];
args.version = JNI_VERSION_1_6;
args.nOptions = 1;
options[0].optionString = classPath;
options[1].optionString = "-verbose";
args.options = options;
args.ignoreUnrecognized = 0;
int rv;
rv = JNI_CreateJavaVM(jvm, (void**)&env, &args);
if (rv < 0 || !env)
printf("Unable to Launch JVM %d\n",rv);
else
printf("Launched JVM! :)\n");
return env;
}
void invoke_class(JNIEnv* env)
{
jclass hello_world_class;
jmethodID main_method;
jmethodID square_method;
jmethodID power_method;
jint number=20;
jint exponent=3;
hello_world_class = env->FindClass("helloWorld/HelloWorld");
if(hello_world_class == NULL){
if(env->ExceptionOccurred()){
env->ExceptionDescribe();
}
printf("Class not found.");
}
else{
main_method = env->GetStaticMethodID(hello_world_class, "main", "([Ljava/lang/String;)V");
square_method = env->GetStaticMethodID(hello_world_class, "square", "(I)I");
power_method = env->GetStaticMethodID(hello_world_class, "power", "(II)I");
env->CallStaticVoidMethod(hello_world_class, main_method, NULL);
printf("%d squared is %d\n", number,
env->CallStaticIntMethod(hello_world_class, square_method, number));
printf("%d raised to the %d power is %d\n", number, exponent,
env->CallStaticIntMethod(hello_world_class, power_method, number, exponent));
}
}
int main(int argc, char **argv)
{
JavaVM *jvm;
JNIEnv *env;
env = create_vm(&jvm);
if(env == NULL)
return 1;
invoke_class(env);
system("PAUSE");
return 0;
}
我已经将HelloWorld.jar放置在我的C++应用程序的根目录中。当它尝试加载hello_world_class时,会抛出以下异常:
java.lang.NoClassDefFoundError: org/apache/log4j/Logger
at helloWorld.HelloWorld.<clinit>(HelloWorld.java:7)
JNI无法找到log4j依赖项,因为它不在HelloWorld.jar内。我尝试将它放在lib文件夹和与HelloWorld.jar相同的文件夹中,但没有成功。我需要把log4j.jar放在哪里,这样JNI才能识别并加载它呢?
非常感谢,我是JNI的新手,请您的回答要清晰易懂。我已经困扰了一整天T.T