Linux下JNI调用

整个实现过程可以分为五步来完成:

1)写一个声明了native的Java文件:

package example;

public   class  TestJNI 
{
    
static  
{
        System.loadLibrary(
" test "
);
    }

    
    
public  native String getNameCPP();
}


2) 使用javah产生对应的CPP头文件:
命令:javah -classpath <path> -jni example.TestJNI -d <out_dir>
生成的头文件example_TestJNI.h如下:

/**/ /*  DO NOT EDIT THIS FILE - it is machine generated  */
#include 
< jni.h >
/**/ /*  Header for class example_TestJNI  */

#ifndef _Included_example_TestJNI
#define  _Included_example_TestJNI
#ifdef __cplusplus
extern   " C "   {
#endif
/**/ /*
 * Class:     example_TestJNI
 * Method:    getNameForCPP
 * Signature: ()Ljava/lang/String;
 
*/

JNIEXPORT jstring JNICALL Java_example_TestJNI_getNameForCPP
  (JNIEnv 
* , jobject);

#ifdef __cplusplus
}

#endif
#endif

3)实现对应的CPP代码:
#include  " example_TestJNI.h "
#include 
< string >

JNIEXPORT jstring JNICALL Java_example_TestJNI_getNameForCPP
  (JNIEnv 
*  env, jobject)
{
    
// TODO 可以在此调用其他的代码
    std:: string  strName  =   " Tower " ;
    
return  env -> NewStringUTF(strName.c_str());
}


4) 编译CPP代码
命 令:g++ -o libtest.so -shared -I<include_path> -I<java_home>/include -I<java_home>/include/linux example_TestJNI.cpp

5)执行
package example;

public   class  Test  {
    
public   static   void  main(String[] args)  {
        TestJNI test 
=   new  TestJNI();
        System.
out .println( " Hello  "   +  test.getNameForCPP());
    }

}


export LD_EXPORT_PATH=<so_path>
java -cp <path> -Djava.library.path=<so_path> example.Test
输出:Hello Tower
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值