Posted on 2012-10-12 16:40
Milo的海域 阅读(3853)
评论(0) 编辑 收藏 所属分类:
Java 、
Linux
直接上C的实现
typedef struct Foo {
int len;
char name[100];
} Foo_t;
JNIEXPORT jint JNICALL
Java_TestJNI_foo(JNIEnv *env, jobject obj, jobject fooObj) {
Foo_t * bar = malloc(sizeof(Foo_t));
jclass clazz;
jfieldID fid;
//init the bar data of C
strcpy(bar->name, "Yachun Miao");
bar->len = strlen(bar->name);
// mapping bar of C to foo
clazz = (*env)->GetObjectClass(env, fooObj);
if (0 == clazz) {
printf("GetObjectClass returned 0\n");
return (-1);
}
fid = (*env)->GetFieldID(env, clazz, "len", "I");
(*env)->SetLongField(env, fooObj, fid, bar->len);
fid = (*env)->GetFieldID(env, clazz, "name", "Ljava/lang/String;");
jstring name = (*env)->NewStringUTF(env, bar->name);
(*env)->SetObjectField(env, fooObj, fid, name);
free(bar);
return 0;
}
对应的Java调用
public class Foo {
protected int len;
protected String name;
}
private static native int foo(Foo fooObj);
public static void main(String args[]) {
System.loadLibrary("mylib");
Foo foo = new Foo();
foo(foo);
System.out.println(foo.name);
System.out.println(foo.len);
} 参考链接
http://www.steveolyo.com/JNI/JNI.html#CSTRCJ
http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/types.html