How to Create a JAVA Native Method

2 篇文章 0 订阅
1) create a Java file:
public class Hello{
        static {
                //System.setProperty("java.library.path", ".");
                System.loadLibrary("hello");
        }
        public static void main(String[] args){
                new Hello().sayHello();
        }


        public native void sayHello();


        public static String get(int index){
                System.out.println("===="+index);
                //return null;
                return null;
        }


}


2)compile JAVA code
javac Hello.java


3)create an CPP header file Hello.h


#include <jni.h>  
/* Header for class HelloJni */  
#ifndef _Included_HelloJni  
#define _Included_HelloJni  
#ifdef __cplusplus  
extern "C" {  
#endif  
JNIEXPORT void JNICALL Java_Hello_sayHello (JNIEnv *, jclass);  
#ifdef __cplusplus  
}  
#endif  
#endif


4)create an CPP file Hello.cpp


#include "Hello.h"
JNIEXPORT void JNICALL Java_Hello_sayHello(JNIEnv *env, jclass cls)
{
       printf("HelloWorld");
       
       //invoke the method from JAVA class
        cls = env->FindClass("Hello");
        //Here the 3rd parameter is the signature of a method which could get by 'javap -s -private Hello'
        jmethodID mid_getFirst = env->GetStaticMethodID(cls,"get","(I)Ljava/lang/String;");
        //jobject obj = env->AllocObject(cls); //here is trying to allocate a space for new object
        jstring jfirst = (jstring)env->CallStaticObjectMethod(cls, mid_getFirst,10);


        mid_getFirst = env->GetStaticMethodID(cls,"get","(I)Ljava/lang/String;");
        jfirst = (jstring)env->CallStaticObjectMethod(cls, mid_getFirst, 10);


        printf("\nsuccess\n");
}  


5)compile CPP code
g++ -I $JAVA_HOME/include -I $JAVA_HOME/include/linux Hello.cpp -fPIC -shared -o libhello.so


6)run JAVA file
java -Djava.library.path=. Hello


//To debug the core file we use the command gdb then tc


Have a nice day!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值