小弟最近有个项目要用到jni来实现,在jni中需要引用自己写的类来返回某些值,但是在jni中使用FindClass,如果该类不是java自带的就会返回null,求解决方法
以下是测试代码:
test.A.java //自己定义的类,希望jni通过该类来返回数据
package test;
public class A
{
public int num;
}
test.B.java //测试类,看看jni是否能够成功返回A的对象
package test;
public class B
{
public static native A getA();
static
{
System.loadLibrary("A");
}
public static void main(String[] args)
{
System.out.println(getA().num);
}
}
test_B.h //jni的头文件
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class test_B */
#ifndef _Included_test_B
#define _Included_test_B
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: test_B
* Method: getA
* Signature: ()Ltest/A;
*/
JNIEXPORT jobject JNICALL Java_test_B_getA
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif
test_B.c //jni的实现文件
FindClass
#include "test_B.h"
/*
* Class: test_B
* Method: getA
* Signature: ()Ltest/A;
*/
JNIEXPORT jobject JNICALL Java_test_B_getA
(JNIEnv * env, jclass cl)
{
jclass class_A = (*env)->FindClass(env, "test.A"); //我已经调试过了,这句执行后class_A的结果为null
jfieldID fid_A_num = (*env)->GetFieldID(env, class_A, "num", "I");
jmethodID mid_A = (*env)->GetMethodID(env, class_A, "<init>", "()V");
jobject obj_A_a = (*env)->NewObject(env, class_A, mid_A);
(*env)->SetIntField(env, obj_A_a, fid_A_num, 100);
return obj_A_a;
}
jclass FindClass(JNIEnv *env, const char *name);
This function loads a locally-defined class. It searches the directories and zip files specified by the CLASSPATH environment variable for the class with the specified name.
LINKAGE:
Index 6 in the JNIEnv interface function table.
PARAMETERS:
env: the JNI interface pointer.
name: a fully-qualified class name (that is, a package name, delimited by “/”, followed by the class name). If the name begins with “[“ (the array signature character), it returns an array class. The string is encoded in modified UTF-8.
看上边,要以"/"分隔而不是"."
最好不要再C中使用Java对象,你如果需要处理返回数据的话,可以定义字节数组作为一个方法的参数,这个Java和C通用,在Java中你自己再根据得到的字节数组把数据解析成对象