zoukankan      html  css  js  c++  java
  • java通过JNI接口调用C语言-初级

    JNI(java native interface):即java本地调用C的接口。

    先看整体运行:

    下面是过程:

    #vim test.java

     1 public class test{
     2     
     3     public native static int add(int a, int b);  //指明本地函数
     4     static{
     5         System.loadLibrary("add");               //指定动态库
     6     };
     7     
     8     public static void main(String args[]){
     9         
    10         int ret = 0;
    11 
    12         ret = add(6, 8);
    13     
    14         System.out.println("hello world! " + ret + "
    ");
    15     }
    16 };

    既然指定了动态库,那么这个库从何而来?对新手来说使用javah 这个命令就可以了,根据这个命令生成的头文件生成库。

    #javac test.java

    #javah -jni test

    此时生成了test.h文件,修改如下:

    #vim test.h

    1 #include <jni.h>
    2 jint Java_test_add (JNIEnv *env, jclass obj, jint a, jint b)
    3 {
    4     return a + b;
    5 }

    把这个头文件变成.c文件,不解释;注意:头文件没有的需要指定路径,我这里之前已经配置好了的。

    #mv test.h test.c

    下面开始生成动态库:

    #gcc -c -fPIC test.c -o test.o          //-fPIC指定与位置无关

    #gcc -shared test.o -o libadd.so        //链接生成动态库

    最后执行java:

    #LD_LIBRARY_PATH=. java test         //指定库的路径为本目录

  • 相关阅读:
    [转]数据类型和Json格式
    maven 配置阿里云仓库
    maven windows 环境变量
    jdk windows环境变量
    springcloud hystrix 部分参数整理
    springboot 解决 woff2、ttf 跨域无法解析问题
    centos7 mysql5.7 rpm 安装
    centos7.3 chrome 安装
    springboot 1.5.X junit测试
    centos7 配置ftp访问
  • 原文地址:https://www.cnblogs.com/luoxiang/p/4192564.html
Copyright © 2011-2022 走看看