我正在尝试使用 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 的新手,所以请在您的回答中明确。我整天都在这个错误TT