这里不在重复Java JNI 的开发过程了,不熟悉的同学请参考:Java JNI HelloWorld
直接上主要代码:
VarJNI.java
package com.example.jni;
public class VarJNI {
static {
System.loadLibrary("varjni");
}
private int number = 9;
private String content = "I'm from Java!";
public native void changeValue();
public static void main(String[] args) throws Exception {
VarJNI item = new VarJNI();
System.out.println("before call number: " + item.number);
System.out.println("before call content: " + item.content);
item.changeValue();
System.out.println("after call number: " + item.number);
System.out.println("after call content: " + item.content);
}
}
varjni.cpp
// varjni.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "com_example_jni_VarJNI.h"
#include <iostream>
#include <math.h>
/*
* Class: com_example_jni_VarJNI
* Method: changeValue
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_example_jni_VarJNI_changeValue
(JNIEnv * env, jobject obj) {
jclass clazz = env->GetObjectClass(obj);
jfieldID int_fieldID = env->GetFieldID(clazz, "number", "I");
jint number = env->GetIntField(obj, int_fieldID);
//change number value
number = (int)pow(number, 2);
env->SetIntField(obj, int_fieldID, number);
//be careful Ljava/lang/String
jfieldID string_fieldID = env->GetFieldID(clazz, "content", "Ljava/lang/String;");
jstring content = (jstring)env->GetObjectField(obj, string_fieldID);
const char* cc = env->GetStringUTFChars(content, 0);
env->ReleaseStringUTFChars(content, cc);
char hello[] = "I'm from C++!\n";
jstring jhello = env->NewStringUTF(hello);
//change content value
env->SetObjectField(obj, string_fieldID, jhello);
return;
}
ok!