欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java JNI入门篇——C++访问并修改Java中的变量,jni入门篇

来源: javaer 分享于  点击 22374 次 点评:183

Java JNI入门篇——C++访问并修改Java中的变量,jni入门篇


这里不在重复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!

相关文章

    暂无相关文章
相关栏目:

用户点评